<!Doctype html>
<html>
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
	<meta name="viewport" content="width=device-width, initial-scale=1.0" />
	<title>Python3 面向对象 | 菜鸟教程</title>

  <meta name='robots' content='max-image-preview:large' />
<link rel='stylesheet' id='classic-theme-styles-css' href='../0/classic-themes.min.css?ver=6.2' type='text/css' media='all' />
<link rel="canonical" href="../python3/python3-class.html" />
<meta name="keywords" content="Python3 面向对象">
<meta name="description" content="Python3 面向对象   Python从设计之初就已经是一门面向对象的语言，正因为如此，在Python中创建一个类和对象是很容易的。本章节我们将详细介绍Python的面向对象编程。   如果你以前没有接触过面向对象的编程语言，那你可能需要先了解一些面向对象语言的一些基本特征，在头脑里头形成一个基本的面向对象的概念，这样有助于你更容易的学习Python的面向对象编程。   接下来我们先来简单的了解下面向对象的一些基本特征。      ..">
		
	<link rel="shortcut icon" href="https://static.runoob.com/images/favicon.ico">
	<link rel="stylesheet" href="../0/style.css?v=1.170" type="text/css" media="all" />	
	<link rel="stylesheet" href="../0/font-awesome.min.css" media="all" />	
  <!--[if gte IE 9]><!-->
  <script src=""></script>
  <!--<![endif]-->
  <!--[if lt IE 9]>
     <script src=""></script>
     <script src=""></script>
  <![endif]-->
  <link rel="apple-touch-icon" href="https://static.runoob.com/images/icon/mobile-icon.png"/>
  <meta name="apple-mobile-web-app-title" content="菜鸟教程">
</head>
<body>

<!--  头部 -->
<div class="container logo-search">

  <div class="col search row-search-mobile">
    <form action="index.php">
      <input class="placeholder" placeholder="搜索……" name="s" autocomplete="off">
      
    </form>
  </div>

  <div class="row">
    <div class="col logo">
      <h1><a href="../">菜鸟教程 -- 学的不仅是技术，更是梦想！</a></h1>
    </div>
        <div class="col right-list"> 
    <button class="btn btn-responsive-nav btn-inverse" data-toggle="collapse" data-target=".nav-main-collapse" id="pull" style=""> <i class="fa fa-navicon"></i> </button>
    </div>
        
    <div class="col search search-desktop last">
      <div class="search-input" >
      <form action="//www.runoob.com/" target="_blank">
        <input class="placeholder" id="s" name="s" placeholder="搜索……"  autocomplete="off" style="height: 44px;">
      </form>
      
      </div>
    </div>
  </div>
</div>



<!-- 导航栏 -->
<!-- 导航栏 -->
<div class="container navigation">
	<div class="row">
		<div class="col nav">
			<ul class="pc-nav" id="runoob-detail-nav">
				<li><a href="../">首页</a></li>
				<li><a href="../html/html-tutorial.html">HTML</a></li>
				<li><a href="../css/css-tutorial.html">CSS</a></li>
				<li><a href="../js/js-tutorial.html">JavaScript</a></li>
				<li><a href="javascript:void(0);" data-id="vue">Vue</a></li>
				<li><a href="javascript:void(0);" data-id="bootstrap">Bootstrap</a></li>
				<li><a href="../nodejs/nodejs-tutorial.html">NodeJS</a></li>
				<li><a href="../python3/python3-tutorial.html">Python3</a></li>
				<li><a href="../python/python-tutorial.html">Python2</a></li>
				<li><a href="../java/java-tutorial.html">Java</a></li>
				<li><a href="../cprogramming/c-tutorial.html">C</a></li>
				<li><a href="../cplusplus/cpp-tutorial.html">C++</a></li>
				<li><a href="../csharp/csharp-tutorial.html">C#</a></li>
				<li><a href="../go/go-tutorial.html">Go</a></li>
				<li><a href="../sql/sql-tutorial.html">SQL</a></li>
				<li><a href="../linux/linux-tutorial.html">Linux</a></li>
				<li><a href="../jquery/jquery-tutorial.html">jQuery</a></li>
				<li><a href="../browser-history">本地书签</a></li>
				<!--
			
				<li><a href="../w3cnote/knowledge-start.html" style="font-weight: bold;" onclick="_hmt.push(['_trackEvent', '星球', 'click', 'start'])" title="我的圈子">我的圈子</a></li>				
				<li><a href="javascript:;" class="runoob-pop">登录</a></li>
				-->
      		</ul>
			<ul class="mobile-nav">
				<li><a href="../">首页</a></li>
				<li><a href="../html/html-tutorial.html">HTML</a></li>
				<li><a href="../css/css-tutorial.html">CSS</a></li>
				<li><a href="../js/js-tutorial.html">JS</a></li>
				<li><a href="../browser-history">本地书签</a></li>
				<li><a href="javascript:void(0)" class="search-reveal">Search</a> </li>
			</ul>
			
		</div>
	</div>
</div>

<div class="container sub-navigation sub-navigation-articles" style="display:none">
	<div class="row">
		<div class="col nav-sub">
		<ul id="python">
			<li class="cat-item"><a href="../python3/python3-tutorial.html">Python3 教程 <i class="fa fa-external-link" aria-hidden="true"></i></a></li>
			<li class="cat-item"><a href="../python/python-tutorial.html">Python2 教程 <i class="fa fa-external-link" aria-hidden="true"></i></a></li>
		</ul>
		<ul id="vue">
			<li class="cat-item"><a href="../vue3/vue3-tutorial.html">Vue3 教程 <i class="fa fa-external-link" aria-hidden="true"></i></a></li>
			<li class="cat-item"><a href="../vue/vue-tutorial.html">vue2 教程 <i class="fa fa-external-link" aria-hidden="true"></i></a></li>
		</ul>

		<ul id="bootstrap">
			<li class="cat-item"><a href="../bootstrap/bootstrap-tutorial.html">Bootstrap3 教程 <i class="fa fa-external-link" aria-hidden="true"></i></a></li>
			<li class="cat-item"><a href="../bootstrap4/bootstrap4-tutorial.html">Bootstrap4 教程 <i class="fa fa-external-link" aria-hidden="true"></i></a></li>
			<li class="cat-item"><a href="../bootstrap5/bootstrap5-tutorial.html">Bootstrap5 教程 <i class="fa fa-external-link" aria-hidden="true"></i></a></li>
			<li class="cat-item"><a href="../bootstrap/bootstrap-v2-tutorial.html">Bootstrap2 教程 <i class="fa fa-external-link" aria-hidden="true"></i></a></li>
		</ul>
		</div>
	</div>
</div><!--  内容  -->
<div class="container main">
	<!-- 中间 -->
	<div class="row">
	
<div class="runoob-col-md2">
<div class="left-column">
	<div class="tab" style="overflow: hidden;text-overflow: ellipsis;white-space: nowrap;">
	<i class="fa fa-list" aria-hidden="true"></i> 
	<span>Python 3 教程</span>
	<a data-cate="124" href="javascript:void(0);" title="夜间模式"  id="moon"><i class="fa fa-moon-o" aria-hidden="true" style="line-height: 28px;font-size: 1.2em;margin: 2px 4px 0;"></i></a>
	<a data-cate="124" style="display:none;" href="javascript:void(0);" title="日间模式"  id="sun" ><i class="fa fa-sun-o" aria-hidden="true" style="line-height: 28px;font-size: 1.2em;margin: 2px 4px 0;line-height: 28px;
}"></i></a>

	</div>
	<div class="sidebar-box gallery-list">
		<div class="design" id="leftcolumn">
						<a target="_top" title="Python3 教程"  href="../python3/python3-tutorial.html" >
			Python3 教程			</a>
			<a target="_top" title="Python3 简介" href="python3-intro.html" > Python3 简介 </a>
<a target="_top" title="Python3 环境搭建" href="python3-install.html" > Python3 环境搭建</a>
<a target="_top" title="Python3 VScode" href="python-vscode-setup.html"> Python3 VScode </a>
<a target="_top" title="Python3 基础语法" href="python3-basic-syntax.html" > Python3 基础语法 </a>
<a target="_top" title="Python3 基本数据类型" href="python3-data-type.html" > Python3 基本数据类型 </a>
<a target="_top" title="Python3  数据类型转换" href="python3-type-conversion.html" > Python3 数据类型转换 </a>
			<a target="_top" title="Python3 解释器"  href="../python3/python3-interpreter.html" >
			Python3 解释器			</a>
						<a target="_top" title="Python3 注释"  href="../python3/python3-comment.html" >
			Python3 注释			</a>
			<a target="_top" title="Python3 运算符" href="python3-basic-operators.html"> Python3 运算符 </a>			<a target="_top" title="Python3 数字(Number)"  href="../python3/python3-number.html" >
			Python3 数字(Number)			</a>
						<a target="_top" title="Python3 字符串"  href="../python3/python3-string.html" >
			Python3 字符串			</a>
						<a target="_top" title="Python3 列表"  href="../python3/python3-list.html" >
			Python3 列表			</a>
			<a target="_top" title="Python3 元组" href="python3-tuple.html"> Python3 元组 </a>
<a target="_top" title="Python3 字典" href="python3-dictionary.html"> Python3 字典</a>
<a target="_top" title="Python3 集合" href="python3-set.html"> Python3 集合</a>			<a target="_top" title="Python3 条件控制"  href="../python3/python3-conditional-statements.html" >
			Python3 条件控制			</a>
						<a target="_top" title="Python3 循环语句"  href="../python3/python3-loop.html" >
			Python3 循环语句			</a>
			<a target="_top" title="Python3 编程第一步" href="python3-step1.html"> Python3 编程第一步</a>
<a target="_top" title="Python3 推导式" href="python-comprehensions.html" > Python3 推导式 </a>
<a target="_top" title="Python3 迭代器与生成器" href="python3-iterator-generator.html"> Python3 迭代器与生成器</a>			<a target="_top" title="Python3 函数"  href="../python3/python3-function.html" >
			Python3 函数			</a>
						<a target="_top" title="Python3 数据结构"  href="../python3/python3-data-structure.html" >
			Python3 数据结构			</a>
						<a target="_top" title="Python3 模块"  href="../python3/python3-module.html" >
			Python3 模块			</a>
						<a target="_top" title="Python3 输入和输出"  href="../python3/python3-inputoutput.html" >
			Python3 输入和输出			</a>
			<a target="_top" title="Python3 File" href="python3-file-methods.html"> Python3 File </a>
<a target="_top" title="Python3 OS" href="python3-os-file-methods.html"> Python3 OS </a>			<a target="_top" title="Python3 错误和异常"  href="../python3/python3-errors-execptions.html" >
			Python3 错误和异常			</a>
						<a target="_top" title="Python3 面向对象"  href="../python3/python3-class.html" >
			Python3 面向对象			</a>
			<a target="_top" title=" Python3 命名空间/作用域" href="../python3/python3-namespace-scope.html"> Python3 命名空间/作用域</a>			<a target="_top" title="Python3 标准库概览"  href="../python3/python3-stdlib.html" >
			Python3 标准库概览			</a>
						<a target="_top" title="Python3 实例"  href="../python3/python3-examples.html" >
			Python3 实例			</a>
			<a target="_blank" title="Python 测验" href="../quiz/python-quiz.html"> Python 测验 </a>
<br><h2 class="left"><span class="left_h2">Python3</span> 高级教程</h2>			<a target="_top" title="Python3 正则表达式"  href="../python3/python3-reg-expressions.html" >
			Python3 正则表达式			</a>
						<a target="_top" title="Python3 CGI编程"  href="../python3/python3-cgi-programming.html" >
			Python3 CGI编程			</a>
			<a target="_top" title="Python MySQL - mysql-connector 驱动" href="python-mysql-connector.html">Python3 MySQL(mysql-connector)</a>			<a target="_top" title="Python3 MySQL 数据库连接 &#8211; PyMySQL 驱动"  href="../python3/python3-mysql.html" >
			Python3 MySQL(PyMySQL)			</a>
						<a target="_top" title="Python3 网络编程"  href="../python3/python3-socket.html" >
			Python3 网络编程			</a>
						<a target="_top" title="Python3 SMTP发送邮件"  href="../python3/python3-smtp.html" >
			Python3 SMTP发送邮件			</a>
						<a target="_top" title="Python3 多线程"  href="../python3/python3-multithreading.html" >
			Python3 多线程			</a>
						<a target="_top" title="Python3 XML 解析"  href="../python3/python3-xml-processing.html" >
			Python3 XML 解析			</a>
						<a target="_top" title="Python3 JSON 数据解析"  href="../python3/python3-json.html" >
			Python3 JSON			</a>
						<a target="_top" title="Python3 日期和时间"  href="../python3/python3-date-time.html" >
			Python3 日期和时间			</a>
						<a target="_top" title="Python3 内置函数"  href="../python3/python3-built-in-functions.html" >
			Python3 内置函数			</a>
						<a target="_top" title="Python MongoDB"  href="../python3/python-mongodb.html" >
			Python3 MongoDB			</a>
			<a target="_top" title="Python3 urllib" href="python-urllib.html"> Python3 urllib</a>			<a target="_top" title="Python uWSGI  安装配置"  href="../python3/python-uwsgi.html" >
			Python uWSGI  安装配置			</a>
						<a target="_top" title="Python3 pip"  href="../python3/python3-pip.html" >
			Python3 pip			</a>
						<a target="_top" title="Python3 operator 模块"  href="../python3/python-operator.html" >
			Python3 operator			</a>
						<a target="_top" title="Python math 模块"  href="../python3/python-math.html" >
			Python math			</a>
						<a target="_top" title="Python requests 模块"  href="../python3/python-requests.html" >
			Python requests			</a>
						<a target="_top" title="Python random 模块"  href="../python3/python-random.html" >
			Python random			</a>
						<a target="_top" title="Python 有用的资源"  href="../python3/python3-resources.html" >
			Python 有用的资源			</a>
						<a target="_top" title="Python AI 绘画"  href="../python3/python-ai-draw.html" >
			Python AI 绘画			</a>
				
		</div>
	</div>	
</div>
</div>	<div class="col middle-column">
		
	
	<div class="article">
		
		<div class="previous-next-links">
			<div class="previous-design-link"><i style="font-size:16px;" class="fa fa-arrow-left" aria-hidden="true"></i> <a href="../python3/python3-errors-execptions.html" rel="prev"> Python3 错误和异常</a> </div>
			<div class="next-design-link"><a href="../python3/python3-stdlib.html" rel="next"> Python3 标准库概览</a> <i style="font-size:16px;" class="fa fa-arrow-right" aria-hidden="true"></i></div>
		</div>
<div class="article-heading-ad" style="display: block;">
<script async src=""
     crossorigin="anonymous"></script>
<!-- 728*90 固定 -->
<ins class="adsbygoogle"
     style="display:inline-block;width:728px;height:90px"
     data-ad-client="ca-pub-5751451760833794"
     data-ad-slot="2147566827"></ins>
<script>
     (adsbygoogle = window.adsbygoogle || []).push({});
</script>
		</div>
		<div class="article-body">
		
			<div class="article-intro" id="content">
			
			<h1>Python3 面向对象</h1>
<div class="tutintro">
<p>
Python从设计之初就已经是一门面向对象的语言，正因为如此，在Python中创建一个类和对象是很容易的。本章节我们将详细介绍Python的面向对象编程。
</p>
<p>
如果你以前没有接触过面向对象的编程语言，那你可能需要先了解一些面向对象语言的一些基本特征，在头脑里头形成一个基本的面向对象的概念，这样有助于你更容易的学习Python的面向对象编程。
</p>
<p>
接下来我们先来简单的了解下面向对象的一些基本特征。
</p>

</div>

<hr>
<h2>面向对象技术简介</h2>
<ul>
<li><strong>类(Class): </strong>用来描述具有相同的属性和方法的对象的集合。它定义了该集合中每个对象所共有的属性和方法。对象是类的实例。</li>
<li><strong>方法：</strong>类中定义的函数。</li>
<li><strong>类变量：</strong>类变量在整个实例化的对象中是公用的。类变量定义在类中且在函数体之外。类变量通常不作为实例变量使用。</li>
<li><strong>数据成员：</strong>类变量或者实例变量用于处理类及其实例对象的相关的数据。</li>
<li><strong>方法重写：</strong>如果从父类继承的方法不能满足子类的需求，可以对其进行改写，这个过程叫方法的覆盖（override），也称为方法的重写。</li>
<li><strong>局部变量：</strong>定义在方法中的变量，只作用于当前实例的类。</li>
<li><strong>实例变量：</strong>在类的声明中，属性是用变量来表示的，这种变量就称为实例变量，实例变量就是一个用 self 修饰的变量。</li>
<li><strong>继承：</strong>即一个派生类（derived class）继承基类（base class）的字段和方法。继承也允许把一个派生类的对象作为一个基类对象对待。例如，有这样一个设计：一个Dog类型的对象派生自Animal类，这是模拟"是一个（is-a）"关系（例图，Dog是一个Animal）。</li>
<li><strong>实例化：</strong>创建一个类的实例，类的具体对象。</li>

<li><strong>对象：</strong>通过类定义的数据结构实例。对象包括两个数据成员（类变量和实例变量）和方法。</li>
</ul>
<p>和其它编程语言相比，Python 在尽可能不增加新的语法和语义的情况下加入了类机制。</p>
<p>Python中的类提供了面向对象编程的所有基本功能：类的继承机制允许多个基类，派生类可以覆盖基类中的任何方法，方法中可以调用基类中的同名方法。
<p>对象可以包含任意数量和类型的数据。
</p>
<h2>类定义</h2>
<p>语法格式如下：</p>
<div class="example"> 
<div class="example_code">
<div class="hl-main"><span class="hl-reserved">class</span><span class="hl-code"> </span><span class="hl-identifier">ClassName</span><span class="hl-code">:
    &lt;</span><span class="hl-identifier">statement</span><span class="hl-code">-</span><span class="hl-number">1</span><span class="hl-code">&gt;
    .
    .
    .
    &lt;</span><span class="hl-identifier">statement</span><span class="hl-code">-</span><span class="hl-identifier">N</span><span class="hl-code">&gt;</span></div>
</div>
</div>
<p>类实例化后，可以使用其属性，实际上，创建一个类之后，可以通过类名访问其属性。</p>
<h2>类对象</h2>
<p>类对象支持两种操作：属性引用和实例化。</p>
<p>
属性引用使用和 Python 中所有的属性引用一样的标准语法：<b>obj.name</b>。</p><p>类对象创建后，类命名空间中所有的命名都是有效属性名。所以如果类定义是这样:</p>
<div class="example"> 
<h2 class="example">实例(Python 3.0+)</h2> 
<div class="example_code">
<div class="hl-main"><span class="hl-comment">#!/usr/bin/python3</span><span class="hl-code">
 
</span><span class="hl-reserved">class</span><span class="hl-code"> </span><span class="hl-identifier">MyClass</span><span class="hl-code">:
    </span><span class="hl-quotes">&quot;&quot;&quot;</span><span class="hl-string">一个简单的类实例</span><span class="hl-quotes">&quot;&quot;&quot;</span><span class="hl-code">
    </span><span class="hl-identifier">i</span><span class="hl-code"> = </span><span class="hl-number">12345</span><span class="hl-code">
    </span><span class="hl-reserved">def</span><span class="hl-code"> </span><span class="hl-identifier">f</span><span class="hl-brackets">(</span><span class="hl-identifier">self</span><span class="hl-brackets">)</span><span class="hl-code">:
        </span><span class="hl-reserved">return</span><span class="hl-code"> </span><span class="hl-quotes">'</span><span class="hl-string">hello world</span><span class="hl-quotes">'</span><span class="hl-code">
 
</span><span class="hl-comment"># 实例化类</span><span class="hl-code">
</span><span class="hl-identifier">x</span><span class="hl-code"> = </span><span class="hl-identifier">MyClass</span><span class="hl-brackets">(</span><span class="hl-brackets">)</span><span class="hl-code">
 
</span><span class="hl-comment"># 访问类的属性和方法</span><span class="hl-code">
</span><span class="hl-identifier">print</span><span class="hl-brackets">(</span><span class="hl-quotes">&quot;</span><span class="hl-string">MyClass 类的属性 i 为：</span><span class="hl-quotes">&quot;</span><span class="hl-code">, </span><span class="hl-identifier">x</span><span class="hl-code">.</span><span class="hl-identifier">i</span><span class="hl-brackets">)</span><span class="hl-code">
</span><span class="hl-identifier">print</span><span class="hl-brackets">(</span><span class="hl-quotes">&quot;</span><span class="hl-string">MyClass 类的方法 f 输出为：</span><span class="hl-quotes">&quot;</span><span class="hl-code">, </span><span class="hl-identifier">x</span><span class="hl-code">.</span><span class="hl-identifier">f</span><span class="hl-brackets">(</span><span class="hl-brackets">)</span><span class="hl-brackets">)</span></div>
</div>
</div>



<p>以上创建了一个新的类实例并将该对象赋给局部变量 x，x 为空的对象。</p>
<p>执行以上程序输出结果为：</p>
<pre>
MyClass 类的属性 i 为： 12345
MyClass 类的方法 f 输出为： hello world
</pre>
<hr>
<p>类有一个名为 __init__() 的特殊方法（<strong>构造方法</strong>），该方法在类实例化时会自动调用，像下面这样：
</p>
<div class="example"> 
<div class="example_code">
<div class="hl-main"><span class="hl-reserved">def</span><span class="hl-code"> </span><span class="hl-identifier">__init__</span><span class="hl-brackets">(</span><span class="hl-identifier">self</span><span class="hl-brackets">)</span><span class="hl-code">:
    </span><span class="hl-identifier">self</span><span class="hl-code">.</span><span class="hl-identifier">data</span><span class="hl-code"> = </span><span class="hl-brackets">[</span><span class="hl-brackets">]</span></div>
</div>
</div>

<p>类定义了 __init__() 方法，类的实例化操作会自动调用 __init__() 方法。如下实例化类 MyClass，对应的 __init__() 方法就会被调用:</p>
<pre>
x = MyClass()
</pre>
<p>当然， __init__() 方法可以有参数，参数通过 __init__() 传递到类的实例化操作上。例如:
</p>
<div class="example"> 
<h2 class="example">实例(Python 3.0+)</h2> 
<div class="example_code">
<div class="hl-main"><span class="hl-comment">#!/usr/bin/python3</span><span class="hl-code">
 
</span><span class="hl-reserved">class</span><span class="hl-code"> </span><span class="hl-identifier">Complex</span><span class="hl-code">:
    </span><span class="hl-reserved">def</span><span class="hl-code"> </span><span class="hl-identifier">__init__</span><span class="hl-brackets">(</span><span class="hl-identifier">self</span><span class="hl-code">, </span><span class="hl-identifier">realpart</span><span class="hl-code">, </span><span class="hl-identifier">imagpart</span><span class="hl-brackets">)</span><span class="hl-code">:
        </span><span class="hl-identifier">self</span><span class="hl-code">.</span><span class="hl-identifier">r</span><span class="hl-code"> = </span><span class="hl-identifier">realpart</span><span class="hl-code">
        </span><span class="hl-identifier">self</span><span class="hl-code">.</span><span class="hl-identifier">i</span><span class="hl-code"> = </span><span class="hl-identifier">imagpart</span><span class="hl-code">
</span><span class="hl-identifier">x</span><span class="hl-code"> = </span><span class="hl-identifier">Complex</span><span class="hl-brackets">(</span><span class="hl-number">3.0</span><span class="hl-code">, -</span><span class="hl-number">4.5</span><span class="hl-brackets">)</span><span class="hl-code">
</span><span class="hl-identifier">print</span><span class="hl-brackets">(</span><span class="hl-identifier">x</span><span class="hl-code">.</span><span class="hl-identifier">r</span><span class="hl-code">, </span><span class="hl-identifier">x</span><span class="hl-code">.</span><span class="hl-identifier">i</span><span class="hl-brackets">)</span><span class="hl-code">   </span><span class="hl-comment"># 输出结果：3.0 -4.5</span></div>
</div>
</div>
<h3>self代表类的实例，而非类</h3>
<p>类的方法与普通的函数只有一个特别的区别——它们必须有一个额外的<strong>第一个参数名称</strong>, 按照惯例它的名称是 self。</p>
<div class="example"> 
<div class="example_code">
<div class="hl-main"><span class="hl-reserved">class</span><span class="hl-code"> </span><span class="hl-identifier">Test</span><span class="hl-code">:
    </span><span class="hl-reserved">def</span><span class="hl-code"> </span><span class="hl-identifier">prt</span><span class="hl-brackets">(</span><span class="hl-identifier">self</span><span class="hl-brackets">)</span><span class="hl-code">:
        </span><span class="hl-identifier">print</span><span class="hl-brackets">(</span><span class="hl-identifier">self</span><span class="hl-brackets">)</span><span class="hl-code">
        </span><span class="hl-identifier">print</span><span class="hl-brackets">(</span><span class="hl-identifier">self</span><span class="hl-code">.</span><span class="hl-identifier">__class__</span><span class="hl-brackets">)</span><span class="hl-code">
 
</span><span class="hl-identifier">t</span><span class="hl-code"> = </span><span class="hl-identifier">Test</span><span class="hl-brackets">(</span><span class="hl-brackets">)</span><span class="hl-code">
</span><span class="hl-identifier">t</span><span class="hl-code">.</span><span class="hl-identifier">prt</span><span class="hl-brackets">(</span><span class="hl-brackets">)</span></div>
</div>
</div>
<p>以上实例执行结果为：</p>
<pre>
&lt;__main__.Test instance at 0x100771878&gt;
__main__.Test
</pre>
<p>从执行结果可以很明显的看出，self 代表的是类的实例，代表当前对象的地址，而 self.class 则指向类。</p>
<p>self 不是 python 关键字，我们把他换成 runoob 也是可以正常执行的:</p>

<div class="example"> 
<div class="example_code">
<div class="hl-main"><span class="hl-reserved">class</span><span class="hl-code"> </span><span class="hl-identifier">Test</span><span class="hl-code">:
    </span><span class="hl-reserved">def</span><span class="hl-code"> </span><span class="hl-identifier">prt</span><span class="hl-brackets">(</span><span class="hl-identifier">runoob</span><span class="hl-brackets">)</span><span class="hl-code">:
        </span><span class="hl-identifier">print</span><span class="hl-brackets">(</span><span class="hl-identifier">runoob</span><span class="hl-brackets">)</span><span class="hl-code">
        </span><span class="hl-identifier">print</span><span class="hl-brackets">(</span><span class="hl-identifier">runoob</span><span class="hl-code">.</span><span class="hl-identifier">__class__</span><span class="hl-brackets">)</span><span class="hl-code">
 
</span><span class="hl-identifier">t</span><span class="hl-code"> = </span><span class="hl-identifier">Test</span><span class="hl-brackets">(</span><span class="hl-brackets">)</span><span class="hl-code">
</span><span class="hl-identifier">t</span><span class="hl-code">.</span><span class="hl-identifier">prt</span><span class="hl-brackets">(</span><span class="hl-brackets">)</span></div>
</div>
</div><p>以上实例执行结果为：</p>
<pre>
&lt;__main__.Test instance at 0x100771878&gt;
__main__.Test
</pre>
<hr>
<h2>类的方法</h2>
<p>
在类的内部，使用 <span class="marked">def</span> 关键字来定义一个方法，与一般函数定义不同，类方法必须包含参数 self, 且为第一个参数，self 代表的是类的实例。
</p>
<div class="example"> 
<h2 class="example">实例(Python 3.0+)</h2> 
<div class="example_code">
<div class="hl-main"><span class="hl-comment">#!/usr/bin/python3</span><span class="hl-code">
 
</span><span class="hl-comment">#类定义</span><span class="hl-code">
</span><span class="hl-reserved">class</span><span class="hl-code"> </span><span class="hl-identifier">people</span><span class="hl-code">:
    </span><span class="hl-comment">#定义基本属性</span><span class="hl-code">
    </span><span class="hl-identifier">name</span><span class="hl-code"> = </span><span class="hl-quotes">'</span><span class="hl-quotes">'</span><span class="hl-code">
    </span><span class="hl-identifier">age</span><span class="hl-code"> = </span><span class="hl-number">0</span><span class="hl-code">
    </span><span class="hl-comment">#定义私有属性,私有属性在类外部无法直接进行访问</span><span class="hl-code">
    </span><span class="hl-identifier">__weight</span><span class="hl-code"> = </span><span class="hl-number">0</span><span class="hl-code">
    </span><span class="hl-comment">#定义构造方法</span><span class="hl-code">
    </span><span class="hl-reserved">def</span><span class="hl-code"> </span><span class="hl-identifier">__init__</span><span class="hl-brackets">(</span><span class="hl-identifier">self</span><span class="hl-code">,</span><span class="hl-identifier">n</span><span class="hl-code">,</span><span class="hl-identifier">a</span><span class="hl-code">,</span><span class="hl-identifier">w</span><span class="hl-brackets">)</span><span class="hl-code">:
        </span><span class="hl-identifier">self</span><span class="hl-code">.</span><span class="hl-identifier">name</span><span class="hl-code"> = </span><span class="hl-identifier">n</span><span class="hl-code">
        </span><span class="hl-identifier">self</span><span class="hl-code">.</span><span class="hl-identifier">age</span><span class="hl-code"> = </span><span class="hl-identifier">a</span><span class="hl-code">
        </span><span class="hl-identifier">self</span><span class="hl-code">.</span><span class="hl-identifier">__weight</span><span class="hl-code"> = </span><span class="hl-identifier">w</span><span class="hl-code">
    </span><span class="hl-reserved">def</span><span class="hl-code"> </span><span class="hl-identifier">speak</span><span class="hl-brackets">(</span><span class="hl-identifier">self</span><span class="hl-brackets">)</span><span class="hl-code">:
        </span><span class="hl-identifier">print</span><span class="hl-brackets">(</span><span class="hl-quotes">&quot;</span><span class="hl-string">%s 说: 我 %d 岁。</span><span class="hl-quotes">&quot;</span><span class="hl-code"> %</span><span class="hl-brackets">(</span><span class="hl-identifier">self</span><span class="hl-code">.</span><span class="hl-identifier">name</span><span class="hl-code">,</span><span class="hl-identifier">self</span><span class="hl-code">.</span><span class="hl-identifier">age</span><span class="hl-brackets">)</span><span class="hl-brackets">)</span><span class="hl-code">
 
</span><span class="hl-comment"># 实例化类</span><span class="hl-code">
</span><span class="hl-identifier">p</span><span class="hl-code"> = </span><span class="hl-identifier">people</span><span class="hl-brackets">(</span><span class="hl-quotes">'</span><span class="hl-string">runoob</span><span class="hl-quotes">'</span><span class="hl-code">,</span><span class="hl-number">10</span><span class="hl-code">,</span><span class="hl-number">30</span><span class="hl-brackets">)</span><span class="hl-code">
</span><span class="hl-identifier">p</span><span class="hl-code">.</span><span class="hl-identifier">speak</span><span class="hl-brackets">(</span><span class="hl-brackets">)</span></div>
</div>
</div>
<p>执行以上程序输出结果为：</p>
<pre>
runoob 说: 我 10 岁。
</pre>
<hr>
<h2>继承</h2>

<p>Python 同样支持类的继承，如果一种语言不支持继承，类就没有什么意义。派生类的定义如下所示:</p>
<div class="example"> 
<div class="example_code">
<div class="hl-main"><span class="hl-reserved">class</span><span class="hl-code"> </span><span class="hl-identifier">DerivedClassName</span><span class="hl-brackets">(</span><span class="hl-identifier">BaseClassName</span><span class="hl-brackets">)</span><span class="hl-code">:
    &lt;</span><span class="hl-identifier">statement</span><span class="hl-code">-</span><span class="hl-number">1</span><span class="hl-code">&gt;
    .
    .
    .
    &lt;</span><span class="hl-identifier">statement</span><span class="hl-code">-</span><span class="hl-identifier">N</span><span class="hl-code">&gt;</span></div>
</div>
</div>

<p><p>子类（派生类 DerivedClassName）会继承父类（基类 BaseClassName）的属性和方法。</p>
BaseClassName（实例中的基类名）必须与派生类定义在一个作用域内。除了类，还可以用表达式，基类定义在另一个模块中时这一点非常有用:
</p>
<pre>
class DerivedClassName(modname.BaseClassName):
</pre>
<div class="example"> 
<h2 class="example">实例(Python 3.0+)</h2> 
<div class="example_code">
<div class="hl-main"><span class="hl-comment">#!/usr/bin/python3</span><span class="hl-code">
 
</span><span class="hl-comment">#类定义</span><span class="hl-code">
</span><span class="hl-reserved">class</span><span class="hl-code"> </span><span class="hl-identifier">people</span><span class="hl-code">:
    </span><span class="hl-comment">#定义基本属性</span><span class="hl-code">
    </span><span class="hl-identifier">name</span><span class="hl-code"> = </span><span class="hl-quotes">'</span><span class="hl-quotes">'</span><span class="hl-code">
    </span><span class="hl-identifier">age</span><span class="hl-code"> = </span><span class="hl-number">0</span><span class="hl-code">
    </span><span class="hl-comment">#定义私有属性,私有属性在类外部无法直接进行访问</span><span class="hl-code">
    </span><span class="hl-identifier">__weight</span><span class="hl-code"> = </span><span class="hl-number">0</span><span class="hl-code">
    </span><span class="hl-comment">#定义构造方法</span><span class="hl-code">
    </span><span class="hl-reserved">def</span><span class="hl-code"> </span><span class="hl-identifier">__init__</span><span class="hl-brackets">(</span><span class="hl-identifier">self</span><span class="hl-code">,</span><span class="hl-identifier">n</span><span class="hl-code">,</span><span class="hl-identifier">a</span><span class="hl-code">,</span><span class="hl-identifier">w</span><span class="hl-brackets">)</span><span class="hl-code">:
        </span><span class="hl-identifier">self</span><span class="hl-code">.</span><span class="hl-identifier">name</span><span class="hl-code"> = </span><span class="hl-identifier">n</span><span class="hl-code">
        </span><span class="hl-identifier">self</span><span class="hl-code">.</span><span class="hl-identifier">age</span><span class="hl-code"> = </span><span class="hl-identifier">a</span><span class="hl-code">
        </span><span class="hl-identifier">self</span><span class="hl-code">.</span><span class="hl-identifier">__weight</span><span class="hl-code"> = </span><span class="hl-identifier">w</span><span class="hl-code">
    </span><span class="hl-reserved">def</span><span class="hl-code"> </span><span class="hl-identifier">speak</span><span class="hl-brackets">(</span><span class="hl-identifier">self</span><span class="hl-brackets">)</span><span class="hl-code">:
        </span><span class="hl-identifier">print</span><span class="hl-brackets">(</span><span class="hl-quotes">&quot;</span><span class="hl-string">%s 说: 我 %d 岁。</span><span class="hl-quotes">&quot;</span><span class="hl-code"> %</span><span class="hl-brackets">(</span><span class="hl-identifier">self</span><span class="hl-code">.</span><span class="hl-identifier">name</span><span class="hl-code">,</span><span class="hl-identifier">self</span><span class="hl-code">.</span><span class="hl-identifier">age</span><span class="hl-brackets">)</span><span class="hl-brackets">)</span><span class="hl-code">
 
</span><span class="hl-comment">#单继承示例</span><span class="hl-code">
</span><span class="hl-reserved">class</span><span class="hl-code"> </span><span class="hl-identifier">student</span><span class="hl-brackets">(</span><span class="hl-identifier">people</span><span class="hl-brackets">)</span><span class="hl-code">:
    </span><span class="hl-identifier">grade</span><span class="hl-code"> = </span><span class="hl-quotes">'</span><span class="hl-quotes">'</span><span class="hl-code">
    </span><span class="hl-reserved">def</span><span class="hl-code"> </span><span class="hl-identifier">__init__</span><span class="hl-brackets">(</span><span class="hl-identifier">self</span><span class="hl-code">,</span><span class="hl-identifier">n</span><span class="hl-code">,</span><span class="hl-identifier">a</span><span class="hl-code">,</span><span class="hl-identifier">w</span><span class="hl-code">,</span><span class="hl-identifier">g</span><span class="hl-brackets">)</span><span class="hl-code">:
        </span><span class="hl-comment">#调用父类的构函</span><span class="hl-code">
        </span><span class="hl-identifier">people</span><span class="hl-code">.</span><span class="hl-identifier">__init__</span><span class="hl-brackets">(</span><span class="hl-identifier">self</span><span class="hl-code">,</span><span class="hl-identifier">n</span><span class="hl-code">,</span><span class="hl-identifier">a</span><span class="hl-code">,</span><span class="hl-identifier">w</span><span class="hl-brackets">)</span><span class="hl-code">
        </span><span class="hl-identifier">self</span><span class="hl-code">.</span><span class="hl-identifier">grade</span><span class="hl-code"> = </span><span class="hl-identifier">g</span><span class="hl-code">
    </span><span class="hl-comment">#覆写父类的方法</span><span class="hl-code">
    </span><span class="hl-reserved">def</span><span class="hl-code"> </span><span class="hl-identifier">speak</span><span class="hl-brackets">(</span><span class="hl-identifier">self</span><span class="hl-brackets">)</span><span class="hl-code">:
        </span><span class="hl-identifier">print</span><span class="hl-brackets">(</span><span class="hl-quotes">&quot;</span><span class="hl-string">%s 说: 我 %d 岁了，我在读 %d 年级</span><span class="hl-quotes">&quot;</span><span class="hl-code">%</span><span class="hl-brackets">(</span><span class="hl-identifier">self</span><span class="hl-code">.</span><span class="hl-identifier">name</span><span class="hl-code">,</span><span class="hl-identifier">self</span><span class="hl-code">.</span><span class="hl-identifier">age</span><span class="hl-code">,</span><span class="hl-identifier">self</span><span class="hl-code">.</span><span class="hl-identifier">grade</span><span class="hl-brackets">)</span><span class="hl-brackets">)</span><span class="hl-code">
 
 
 
</span><span class="hl-identifier">s</span><span class="hl-code"> = </span><span class="hl-identifier">student</span><span class="hl-brackets">(</span><span class="hl-quotes">'</span><span class="hl-string">ken</span><span class="hl-quotes">'</span><span class="hl-code">,</span><span class="hl-number">10</span><span class="hl-code">,</span><span class="hl-number">60</span><span class="hl-code">,</span><span class="hl-number">3</span><span class="hl-brackets">)</span><span class="hl-code">
</span><span class="hl-identifier">s</span><span class="hl-code">.</span><span class="hl-identifier">speak</span><span class="hl-brackets">(</span><span class="hl-brackets">)</span></div>
</div>
</div>
<p>执行以上程序输出结果为：</p>
<pre>
ken 说: 我 10 岁了，我在读 3 年级
</pre>
<hr>
<h2>多继承</h2>
<p>Python同样有限的支持多继承形式。多继承的类定义形如下例:</p>
<div class="example"> 
<div class="example_code">
<div class="hl-main"><span class="hl-reserved">class</span><span class="hl-code"> </span><span class="hl-identifier">DerivedClassName</span><span class="hl-brackets">(</span><span class="hl-identifier">Base1</span><span class="hl-code">, </span><span class="hl-identifier">Base2</span><span class="hl-code">, </span><span class="hl-identifier">Base3</span><span class="hl-brackets">)</span><span class="hl-code">:
    &lt;</span><span class="hl-identifier">statement</span><span class="hl-code">-</span><span class="hl-number">1</span><span class="hl-code">&gt;
    .
    .
    .
    &lt;</span><span class="hl-identifier">statement</span><span class="hl-code">-</span><span class="hl-identifier">N</span><span class="hl-code">&gt;</span></div>
</div>
</div>
<p>需要注意圆括号中父类的顺序，若是父类中有相同的方法名，而在子类使用时未指定，python从左至右搜索
即方法在子类中未找到时，从左到右查找父类中是否包含方法。</p>
<div class="example"> 
<h2 class="example">实例(Python 3.0+)</h2> 
<div class="example_code">
<div class="hl-main"><span class="hl-comment">#!/usr/bin/python3</span><span class="hl-code">
 
</span><span class="hl-comment">#类定义</span><span class="hl-code">
</span><span class="hl-reserved">class</span><span class="hl-code"> </span><span class="hl-identifier">people</span><span class="hl-code">:
    </span><span class="hl-comment">#定义基本属性</span><span class="hl-code">
    </span><span class="hl-identifier">name</span><span class="hl-code"> = </span><span class="hl-quotes">'</span><span class="hl-quotes">'</span><span class="hl-code">
    </span><span class="hl-identifier">age</span><span class="hl-code"> = </span><span class="hl-number">0</span><span class="hl-code">
    </span><span class="hl-comment">#定义私有属性,私有属性在类外部无法直接进行访问</span><span class="hl-code">
    </span><span class="hl-identifier">__weight</span><span class="hl-code"> = </span><span class="hl-number">0</span><span class="hl-code">
    </span><span class="hl-comment">#定义构造方法</span><span class="hl-code">
    </span><span class="hl-reserved">def</span><span class="hl-code"> </span><span class="hl-identifier">__init__</span><span class="hl-brackets">(</span><span class="hl-identifier">self</span><span class="hl-code">,</span><span class="hl-identifier">n</span><span class="hl-code">,</span><span class="hl-identifier">a</span><span class="hl-code">,</span><span class="hl-identifier">w</span><span class="hl-brackets">)</span><span class="hl-code">:
        </span><span class="hl-identifier">self</span><span class="hl-code">.</span><span class="hl-identifier">name</span><span class="hl-code"> = </span><span class="hl-identifier">n</span><span class="hl-code">
        </span><span class="hl-identifier">self</span><span class="hl-code">.</span><span class="hl-identifier">age</span><span class="hl-code"> = </span><span class="hl-identifier">a</span><span class="hl-code">
        </span><span class="hl-identifier">self</span><span class="hl-code">.</span><span class="hl-identifier">__weight</span><span class="hl-code"> = </span><span class="hl-identifier">w</span><span class="hl-code">
    </span><span class="hl-reserved">def</span><span class="hl-code"> </span><span class="hl-identifier">speak</span><span class="hl-brackets">(</span><span class="hl-identifier">self</span><span class="hl-brackets">)</span><span class="hl-code">:
        </span><span class="hl-identifier">print</span><span class="hl-brackets">(</span><span class="hl-quotes">&quot;</span><span class="hl-string">%s 说: 我 %d 岁。</span><span class="hl-quotes">&quot;</span><span class="hl-code"> %</span><span class="hl-brackets">(</span><span class="hl-identifier">self</span><span class="hl-code">.</span><span class="hl-identifier">name</span><span class="hl-code">,</span><span class="hl-identifier">self</span><span class="hl-code">.</span><span class="hl-identifier">age</span><span class="hl-brackets">)</span><span class="hl-brackets">)</span><span class="hl-code">
 
</span><span class="hl-comment">#单继承示例</span><span class="hl-code">
</span><span class="hl-reserved">class</span><span class="hl-code"> </span><span class="hl-identifier">student</span><span class="hl-brackets">(</span><span class="hl-identifier">people</span><span class="hl-brackets">)</span><span class="hl-code">:
    </span><span class="hl-identifier">grade</span><span class="hl-code"> = </span><span class="hl-quotes">'</span><span class="hl-quotes">'</span><span class="hl-code">
    </span><span class="hl-reserved">def</span><span class="hl-code"> </span><span class="hl-identifier">__init__</span><span class="hl-brackets">(</span><span class="hl-identifier">self</span><span class="hl-code">,</span><span class="hl-identifier">n</span><span class="hl-code">,</span><span class="hl-identifier">a</span><span class="hl-code">,</span><span class="hl-identifier">w</span><span class="hl-code">,</span><span class="hl-identifier">g</span><span class="hl-brackets">)</span><span class="hl-code">:
        </span><span class="hl-comment">#调用父类的构函</span><span class="hl-code">
        </span><span class="hl-identifier">people</span><span class="hl-code">.</span><span class="hl-identifier">__init__</span><span class="hl-brackets">(</span><span class="hl-identifier">self</span><span class="hl-code">,</span><span class="hl-identifier">n</span><span class="hl-code">,</span><span class="hl-identifier">a</span><span class="hl-code">,</span><span class="hl-identifier">w</span><span class="hl-brackets">)</span><span class="hl-code">
        </span><span class="hl-identifier">self</span><span class="hl-code">.</span><span class="hl-identifier">grade</span><span class="hl-code"> = </span><span class="hl-identifier">g</span><span class="hl-code">
    </span><span class="hl-comment">#覆写父类的方法</span><span class="hl-code">
    </span><span class="hl-reserved">def</span><span class="hl-code"> </span><span class="hl-identifier">speak</span><span class="hl-brackets">(</span><span class="hl-identifier">self</span><span class="hl-brackets">)</span><span class="hl-code">:
        </span><span class="hl-identifier">print</span><span class="hl-brackets">(</span><span class="hl-quotes">&quot;</span><span class="hl-string">%s 说: 我 %d 岁了，我在读 %d 年级</span><span class="hl-quotes">&quot;</span><span class="hl-code">%</span><span class="hl-brackets">(</span><span class="hl-identifier">self</span><span class="hl-code">.</span><span class="hl-identifier">name</span><span class="hl-code">,</span><span class="hl-identifier">self</span><span class="hl-code">.</span><span class="hl-identifier">age</span><span class="hl-code">,</span><span class="hl-identifier">self</span><span class="hl-code">.</span><span class="hl-identifier">grade</span><span class="hl-brackets">)</span><span class="hl-brackets">)</span><span class="hl-code">
 
</span><span class="hl-comment">#另一个类，多重继承之前的准备</span><span class="hl-code">
</span><span class="hl-reserved">class</span><span class="hl-code"> </span><span class="hl-identifier">speaker</span><span class="hl-brackets">(</span><span class="hl-brackets">)</span><span class="hl-code">:
    </span><span class="hl-identifier">topic</span><span class="hl-code"> = </span><span class="hl-quotes">'</span><span class="hl-quotes">'</span><span class="hl-code">
    </span><span class="hl-identifier">name</span><span class="hl-code"> = </span><span class="hl-quotes">'</span><span class="hl-quotes">'</span><span class="hl-code">
    </span><span class="hl-reserved">def</span><span class="hl-code"> </span><span class="hl-identifier">__init__</span><span class="hl-brackets">(</span><span class="hl-identifier">self</span><span class="hl-code">,</span><span class="hl-identifier">n</span><span class="hl-code">,</span><span class="hl-identifier">t</span><span class="hl-brackets">)</span><span class="hl-code">:
        </span><span class="hl-identifier">self</span><span class="hl-code">.</span><span class="hl-identifier">name</span><span class="hl-code"> = </span><span class="hl-identifier">n</span><span class="hl-code">
        </span><span class="hl-identifier">self</span><span class="hl-code">.</span><span class="hl-identifier">topic</span><span class="hl-code"> = </span><span class="hl-identifier">t</span><span class="hl-code">
    </span><span class="hl-reserved">def</span><span class="hl-code"> </span><span class="hl-identifier">speak</span><span class="hl-brackets">(</span><span class="hl-identifier">self</span><span class="hl-brackets">)</span><span class="hl-code">:
        </span><span class="hl-identifier">print</span><span class="hl-brackets">(</span><span class="hl-quotes">&quot;</span><span class="hl-string">我叫 %s，我是一个演说家，我演讲的主题是 %s</span><span class="hl-quotes">&quot;</span><span class="hl-code">%</span><span class="hl-brackets">(</span><span class="hl-identifier">self</span><span class="hl-code">.</span><span class="hl-identifier">name</span><span class="hl-code">,</span><span class="hl-identifier">self</span><span class="hl-code">.</span><span class="hl-identifier">topic</span><span class="hl-brackets">)</span><span class="hl-brackets">)</span><span class="hl-code">
 
</span><span class="hl-comment">#多重继承</span><span class="hl-code">
</span><span class="hl-reserved">class</span><span class="hl-code"> </span><span class="hl-identifier">sample</span><span class="hl-brackets">(</span><span class="hl-identifier">speaker</span><span class="hl-code">,</span><span class="hl-identifier">student</span><span class="hl-brackets">)</span><span class="hl-code">:
    </span><span class="hl-identifier">a</span><span class="hl-code"> =</span><span class="hl-quotes">'</span><span class="hl-quotes">'</span><span class="hl-code">
    </span><span class="hl-reserved">def</span><span class="hl-code"> </span><span class="hl-identifier">__init__</span><span class="hl-brackets">(</span><span class="hl-identifier">self</span><span class="hl-code">,</span><span class="hl-identifier">n</span><span class="hl-code">,</span><span class="hl-identifier">a</span><span class="hl-code">,</span><span class="hl-identifier">w</span><span class="hl-code">,</span><span class="hl-identifier">g</span><span class="hl-code">,</span><span class="hl-identifier">t</span><span class="hl-brackets">)</span><span class="hl-code">:
        </span><span class="hl-identifier">student</span><span class="hl-code">.</span><span class="hl-identifier">__init__</span><span class="hl-brackets">(</span><span class="hl-identifier">self</span><span class="hl-code">,</span><span class="hl-identifier">n</span><span class="hl-code">,</span><span class="hl-identifier">a</span><span class="hl-code">,</span><span class="hl-identifier">w</span><span class="hl-code">,</span><span class="hl-identifier">g</span><span class="hl-brackets">)</span><span class="hl-code">
        </span><span class="hl-identifier">speaker</span><span class="hl-code">.</span><span class="hl-identifier">__init__</span><span class="hl-brackets">(</span><span class="hl-identifier">self</span><span class="hl-code">,</span><span class="hl-identifier">n</span><span class="hl-code">,</span><span class="hl-identifier">t</span><span class="hl-brackets">)</span><span class="hl-code">
 
</span><span class="hl-identifier">test</span><span class="hl-code"> = </span><span class="hl-identifier">sample</span><span class="hl-brackets">(</span><span class="hl-quotes">&quot;</span><span class="hl-string">Tim</span><span class="hl-quotes">&quot;</span><span class="hl-code">,</span><span class="hl-number">25</span><span class="hl-code">,</span><span class="hl-number">80</span><span class="hl-code">,</span><span class="hl-number">4</span><span class="hl-code">,</span><span class="hl-quotes">&quot;</span><span class="hl-string">Python</span><span class="hl-quotes">&quot;</span><span class="hl-brackets">)</span><span class="hl-code">
</span><span class="hl-identifier">test</span><span class="hl-code">.</span><span class="hl-identifier">speak</span><span class="hl-brackets">(</span><span class="hl-brackets">)</span><span class="hl-code">   </span><span class="hl-comment">#方法名同，默认调用的是在括号中参数位置排前父类的方法</span></div>
</div>
</div>
<p>执行以上程序输出结果为：</p>
<pre>
我叫 Tim，我是一个演说家，我演讲的主题是 Python
</pre>
<hr>
<h2>
方法重写</h2><p>
如果你的父类方法的功能不能满足你的需求，你可以在子类重写你父类的方法，实例如下：</p>
<div class="example"> 
<h2 class="example">实例(Python 3.0+)</h2> 
<div class="example_code">
<div class="hl-main"><span class="hl-comment">#!/usr/bin/python3</span><span class="hl-code">
 
</span><span class="hl-reserved">class</span><span class="hl-code"> </span><span class="hl-identifier">Parent</span><span class="hl-code">:        </span><span class="hl-comment"># 定义父类</span><span class="hl-code">
   </span><span class="hl-reserved">def</span><span class="hl-code"> </span><span class="hl-identifier">myMethod</span><span class="hl-brackets">(</span><span class="hl-identifier">self</span><span class="hl-brackets">)</span><span class="hl-code">:
      </span><span class="hl-identifier">print</span><span class="hl-code"> </span><span class="hl-brackets">(</span><span class="hl-quotes">'</span><span class="hl-string">调用父类方法</span><span class="hl-quotes">'</span><span class="hl-brackets">)</span><span class="hl-code">
 
</span><span class="hl-reserved">class</span><span class="hl-code"> </span><span class="hl-identifier">Child</span><span class="hl-brackets">(</span><span class="hl-identifier">Parent</span><span class="hl-brackets">)</span><span class="hl-code">: </span><span class="hl-comment"># 定义子类</span><span class="hl-code">
   </span><span class="hl-reserved">def</span><span class="hl-code"> </span><span class="hl-identifier">myMethod</span><span class="hl-brackets">(</span><span class="hl-identifier">self</span><span class="hl-brackets">)</span><span class="hl-code">:
      </span><span class="hl-identifier">print</span><span class="hl-code"> </span><span class="hl-brackets">(</span><span class="hl-quotes">'</span><span class="hl-string">调用子类方法</span><span class="hl-quotes">'</span><span class="hl-brackets">)</span><span class="hl-code">
 
</span><span class="hl-identifier">c</span><span class="hl-code"> = </span><span class="hl-identifier">Child</span><span class="hl-brackets">(</span><span class="hl-brackets">)</span><span class="hl-code">          </span><span class="hl-comment"># 子类实例</span><span class="hl-code">
</span><span class="hl-identifier">c</span><span class="hl-code">.</span><span class="hl-identifier">myMethod</span><span class="hl-brackets">(</span><span class="hl-brackets">)</span><span class="hl-code">         </span><span class="hl-comment"># 子类调用重写方法</span><span class="hl-code">
</span><span class="hl-builtin">super</span><span class="hl-brackets">(</span><span class="hl-identifier">Child</span><span class="hl-code">,</span><span class="hl-identifier">c</span><span class="hl-brackets">)</span><span class="hl-code">.</span><span class="hl-identifier">myMethod</span><span class="hl-brackets">(</span><span class="hl-brackets">)</span><span class="hl-code"> </span><span class="hl-comment">#用子类对象调用父类已被覆盖的方法</span></div>
</div>
</div>

<p><a href="../python/python-func-super.html" rel="noopener noreferrer" target="_blank">super() 函数</a>是用于调用父类(超类)的一个方法。</p>

<p>执行以上程序输出结果为：</p>
<pre>
调用子类方法
调用父类方法
</pre>
<p><strong>更多文档：</strong></p>
<p><a href="../w3cnote/python-extends-init.html" rel="noopener noreferrer" target="_blank"> Python 子类继承父类构造函数说明 </a></p>
<hr>
<h2>类属性与方法</h2>
<h3>类的私有属性</h3>
<p><strong>__private_attrs</strong>：两个下划线开头，声明该属性为私有，不能在类的外部被使用或直接访问。在类内部的方法中使用时 <strong>self.__private_attrs</strong>。</p>
<h3>类的方法</h3>
<p>在类的内部，使用 def 关键字来定义一个方法，与一般函数定义不同，类方法必须包含参数 <span class="marked">self</span>，且为第一个参数，<span class="marked">self</span> 代表的是类的实例。</p>
<p><span class="marked">self</span> 的名字并不是规定死的，也可以使用 <span class="marked">this</span>，但是最好还是按照约定使用 <span class="marked">self</span>。</p>

<h3>类的私有方法</h3>
<p>
<strong>__private_method</strong>：两个下划线开头，声明该方法为私有方法，只能在类的内部调用 ，不能在类的外部调用。<strong>self.__private_methods</strong>。
</p>
<h3>实例</h3>
<p>类的私有属性实例如下：</p>
<div class="example"> 
<h2 class="example">实例(Python 3.0+)</h2> 
<div class="example_code">
<div class="hl-main"><span class="hl-comment">#!/usr/bin/python3</span><span class="hl-code">
 
</span><span class="hl-reserved">class</span><span class="hl-code"> </span><span class="hl-identifier">JustCounter</span><span class="hl-code">:
    </span><span class="hl-identifier">__secretCount</span><span class="hl-code"> = </span><span class="hl-number">0</span><span class="hl-code">  </span><span class="hl-comment"># 私有变量</span><span class="hl-code">
    </span><span class="hl-identifier">publicCount</span><span class="hl-code"> = </span><span class="hl-number">0</span><span class="hl-code">    </span><span class="hl-comment"># 公开变量</span><span class="hl-code">
 
    </span><span class="hl-reserved">def</span><span class="hl-code"> </span><span class="hl-identifier">count</span><span class="hl-brackets">(</span><span class="hl-identifier">self</span><span class="hl-brackets">)</span><span class="hl-code">:
        </span><span class="hl-identifier">self</span><span class="hl-code">.</span><span class="hl-identifier">__secretCount</span><span class="hl-code"> += </span><span class="hl-number">1</span><span class="hl-code">
        </span><span class="hl-identifier">self</span><span class="hl-code">.</span><span class="hl-identifier">publicCount</span><span class="hl-code"> += </span><span class="hl-number">1</span><span class="hl-code">
        </span><span class="hl-identifier">print</span><span class="hl-code"> </span><span class="hl-brackets">(</span><span class="hl-identifier">self</span><span class="hl-code">.</span><span class="hl-identifier">__secretCount</span><span class="hl-brackets">)</span><span class="hl-code">
 
</span><span class="hl-identifier">counter</span><span class="hl-code"> = </span><span class="hl-identifier">JustCounter</span><span class="hl-brackets">(</span><span class="hl-brackets">)</span><span class="hl-code">
</span><span class="hl-identifier">counter</span><span class="hl-code">.</span><span class="hl-identifier">count</span><span class="hl-brackets">(</span><span class="hl-brackets">)</span><span class="hl-code">
</span><span class="hl-identifier">counter</span><span class="hl-code">.</span><span class="hl-identifier">count</span><span class="hl-brackets">(</span><span class="hl-brackets">)</span><span class="hl-code">
</span><span class="hl-identifier">print</span><span class="hl-code"> </span><span class="hl-brackets">(</span><span class="hl-identifier">counter</span><span class="hl-code">.</span><span class="hl-identifier">publicCount</span><span class="hl-brackets">)</span><span class="hl-code">
</span><span class="hl-identifier">print</span><span class="hl-code"> </span><span class="hl-brackets">(</span><span class="hl-identifier">counter</span><span class="hl-code">.</span><span class="hl-identifier">__secretCount</span><span class="hl-brackets">)</span><span class="hl-code">  </span><span class="hl-comment"># 报错，实例不能访问私有变量</span></div>
</div>
</div>
<p>执行以上程序输出结果为：</p>
<pre>
1
2
2
Traceback (most recent call last):
  File "test.py", line 16, in &lt;module&gt;
    print (counter.__secretCount)  # 报错，实例不能访问私有变量
AttributeError: 'JustCounter' object has no attribute '__secretCount'
</pre>
<p>类的私有方法实例如下：</p>
<div class="example"> 
<h2 class="example">实例(Python 3.0+)</h2> 
<div class="example_code">
<div class="hl-main"><span class="hl-comment">#!/usr/bin/python3</span><span class="hl-code">
 
</span><span class="hl-reserved">class</span><span class="hl-code"> </span><span class="hl-identifier">Site</span><span class="hl-code">:
    </span><span class="hl-reserved">def</span><span class="hl-code"> </span><span class="hl-identifier">__init__</span><span class="hl-brackets">(</span><span class="hl-identifier">self</span><span class="hl-code">, </span><span class="hl-identifier">name</span><span class="hl-code">, </span><span class="hl-identifier">url</span><span class="hl-brackets">)</span><span class="hl-code">:
        </span><span class="hl-identifier">self</span><span class="hl-code">.</span><span class="hl-identifier">name</span><span class="hl-code"> = </span><span class="hl-identifier">name</span><span class="hl-code">       </span><span class="hl-comment"># public</span><span class="hl-code">
        </span><span class="hl-identifier">self</span><span class="hl-code">.</span><span class="hl-identifier">__url</span><span class="hl-code"> = </span><span class="hl-identifier">url</span><span class="hl-code">   </span><span class="hl-comment"># private</span><span class="hl-code">
 
    </span><span class="hl-reserved">def</span><span class="hl-code"> </span><span class="hl-identifier">who</span><span class="hl-brackets">(</span><span class="hl-identifier">self</span><span class="hl-brackets">)</span><span class="hl-code">:
        </span><span class="hl-identifier">print</span><span class="hl-brackets">(</span><span class="hl-quotes">'</span><span class="hl-string">name  : </span><span class="hl-quotes">'</span><span class="hl-code">, </span><span class="hl-identifier">self</span><span class="hl-code">.</span><span class="hl-identifier">name</span><span class="hl-brackets">)</span><span class="hl-code">
        </span><span class="hl-identifier">print</span><span class="hl-brackets">(</span><span class="hl-quotes">'</span><span class="hl-string">url : </span><span class="hl-quotes">'</span><span class="hl-code">, </span><span class="hl-identifier">self</span><span class="hl-code">.</span><span class="hl-identifier">__url</span><span class="hl-brackets">)</span><span class="hl-code">
 
    </span><span class="hl-reserved">def</span><span class="hl-code"> </span><span class="hl-identifier">__foo</span><span class="hl-brackets">(</span><span class="hl-identifier">self</span><span class="hl-brackets">)</span><span class="hl-code">:          </span><span class="hl-comment"># 私有方法</span><span class="hl-code">
        </span><span class="hl-identifier">print</span><span class="hl-brackets">(</span><span class="hl-quotes">'</span><span class="hl-string">这是私有方法</span><span class="hl-quotes">'</span><span class="hl-brackets">)</span><span class="hl-code">
 
    </span><span class="hl-reserved">def</span><span class="hl-code"> </span><span class="hl-identifier">foo</span><span class="hl-brackets">(</span><span class="hl-identifier">self</span><span class="hl-brackets">)</span><span class="hl-code">:            </span><span class="hl-comment"># 公共方法</span><span class="hl-code">
        </span><span class="hl-identifier">print</span><span class="hl-brackets">(</span><span class="hl-quotes">'</span><span class="hl-string">这是公共方法</span><span class="hl-quotes">'</span><span class="hl-brackets">)</span><span class="hl-code">
        </span><span class="hl-identifier">self</span><span class="hl-code">.</span><span class="hl-identifier">__foo</span><span class="hl-brackets">(</span><span class="hl-brackets">)</span><span class="hl-code">
 
</span><span class="hl-identifier">x</span><span class="hl-code"> = </span><span class="hl-identifier">Site</span><span class="hl-brackets">(</span><span class="hl-quotes">'</span><span class="hl-string">菜鸟教程</span><span class="hl-quotes">'</span><span class="hl-code">, </span><span class="hl-quotes">'</span><span class="hl-string">www.runoob.com</span><span class="hl-quotes">'</span><span class="hl-brackets">)</span><span class="hl-code">
</span><span class="hl-identifier">x</span><span class="hl-code">.</span><span class="hl-identifier">who</span><span class="hl-brackets">(</span><span class="hl-brackets">)</span><span class="hl-code">        </span><span class="hl-comment"># 正常输出</span><span class="hl-code">
</span><span class="hl-identifier">x</span><span class="hl-code">.</span><span class="hl-identifier">foo</span><span class="hl-brackets">(</span><span class="hl-brackets">)</span><span class="hl-code">        </span><span class="hl-comment"># 正常输出</span><span class="hl-code">
</span><span class="hl-identifier">x</span><span class="hl-code">.</span><span class="hl-identifier">__foo</span><span class="hl-brackets">(</span><span class="hl-brackets">)</span><span class="hl-code">      </span><span class="hl-comment"># 报错</span></div>
</div>
</div>

<p>以上实例执行结果：</p>
<p><img decoding="async" src="//www.runoob.com/wp-content/uploads/2014/05/F5C2A308-3A88-42B4-B575-C719EB8F1CC4.jpg" width="70%"></p>
<h3>
类的专有方法：</h3>
<ul>
	<li><strong>__init__ :</strong> 构造函数，在生成对象时调用</li>
	<li><strong>__del__ :</strong> 析构函数，释放对象时使用</li>
	<li><strong>__repr__ :</strong> 打印，转换</li>
	<li><strong>__setitem__ :</strong> 按照索引赋值</li>
	<li><strong>__getitem__:</strong> 按照索引获取值</li>
	<li><strong>__len__:</strong> 获得长度</li>
	<li><strong>__cmp__:</strong> 比较运算</li>
	<li><strong>__call__:</strong> 函数调用</li>
	<li><strong>__add__:</strong> 加运算</li>
	<li><strong>__sub__:</strong> 减运算</li>
	<li><strong>__mul__:</strong> 乘运算</li>
	<li><strong>__truediv__:</strong> 除运算</li>
	<li><strong>__mod__:</strong> 求余运算</li>
	<li><strong>__pow__:</strong> 乘方</li>
</ul>
<h3>运算符重载</h3>
<p>Python同样支持运算符重载，我们可以对类的专有方法进行重载，实例如下：</p>
<div class="example"> 
<h2 class="example">实例(Python 3.0+)</h2> 
<div class="example_code">
<div class="hl-main"><span class="hl-comment">#!/usr/bin/python3</span><span class="hl-code">
 
</span><span class="hl-reserved">class</span><span class="hl-code"> </span><span class="hl-identifier">Vector</span><span class="hl-code">:
   </span><span class="hl-reserved">def</span><span class="hl-code"> </span><span class="hl-identifier">__init__</span><span class="hl-brackets">(</span><span class="hl-identifier">self</span><span class="hl-code">, </span><span class="hl-identifier">a</span><span class="hl-code">, </span><span class="hl-identifier">b</span><span class="hl-brackets">)</span><span class="hl-code">:
      </span><span class="hl-identifier">self</span><span class="hl-code">.</span><span class="hl-identifier">a</span><span class="hl-code"> = </span><span class="hl-identifier">a</span><span class="hl-code">
      </span><span class="hl-identifier">self</span><span class="hl-code">.</span><span class="hl-identifier">b</span><span class="hl-code"> = </span><span class="hl-identifier">b</span><span class="hl-code">
 
   </span><span class="hl-reserved">def</span><span class="hl-code"> </span><span class="hl-identifier">__str__</span><span class="hl-brackets">(</span><span class="hl-identifier">self</span><span class="hl-brackets">)</span><span class="hl-code">:
      </span><span class="hl-reserved">return</span><span class="hl-code"> </span><span class="hl-quotes">'</span><span class="hl-string">Vector (%d, %d)</span><span class="hl-quotes">'</span><span class="hl-code"> % </span><span class="hl-brackets">(</span><span class="hl-identifier">self</span><span class="hl-code">.</span><span class="hl-identifier">a</span><span class="hl-code">, </span><span class="hl-identifier">self</span><span class="hl-code">.</span><span class="hl-identifier">b</span><span class="hl-brackets">)</span><span class="hl-code">
   
   </span><span class="hl-reserved">def</span><span class="hl-code"> </span><span class="hl-identifier">__add__</span><span class="hl-brackets">(</span><span class="hl-identifier">self</span><span class="hl-code">,</span><span class="hl-identifier">other</span><span class="hl-brackets">)</span><span class="hl-code">:
      </span><span class="hl-reserved">return</span><span class="hl-code"> </span><span class="hl-identifier">Vector</span><span class="hl-brackets">(</span><span class="hl-identifier">self</span><span class="hl-code">.</span><span class="hl-identifier">a</span><span class="hl-code"> + </span><span class="hl-identifier">other</span><span class="hl-code">.</span><span class="hl-identifier">a</span><span class="hl-code">, </span><span class="hl-identifier">self</span><span class="hl-code">.</span><span class="hl-identifier">b</span><span class="hl-code"> + </span><span class="hl-identifier">other</span><span class="hl-code">.</span><span class="hl-identifier">b</span><span class="hl-brackets">)</span><span class="hl-code">
 
</span><span class="hl-identifier">v1</span><span class="hl-code"> = </span><span class="hl-identifier">Vector</span><span class="hl-brackets">(</span><span class="hl-number">2</span><span class="hl-code">,</span><span class="hl-number">10</span><span class="hl-brackets">)</span><span class="hl-code">
</span><span class="hl-identifier">v2</span><span class="hl-code"> = </span><span class="hl-identifier">Vector</span><span class="hl-brackets">(</span><span class="hl-number">5</span><span class="hl-code">,-</span><span class="hl-number">2</span><span class="hl-brackets">)</span><span class="hl-code">
</span><span class="hl-identifier">print</span><span class="hl-code"> </span><span class="hl-brackets">(</span><span class="hl-identifier">v1</span><span class="hl-code"> + </span><span class="hl-identifier">v2</span><span class="hl-brackets">)</span></div>
</div>
</div>

<p>以上代码执行结果如下所示:</p>
<pre>
Vector(7,8)
</pre>
			<!-- 其他扩展 -->
						
			</div>
			
		</div>
		
		<div class="previous-next-links">
			<div class="previous-design-link"><i style="font-size:16px;" class="fa fa-arrow-left" aria-hidden="true"></i> <a href="../python3/python3-errors-execptions.html" rel="prev"> Python3 错误和异常</a> </div>
			<div class="next-design-link"><a href="../python3/python3-stdlib.html" rel="next"> Python3 标准库概览</a> <i style="font-size:16px;" class="fa fa-arrow-right" aria-hidden="true"></i></div>
		</div>
		<!-- 笔记列表 -->
		<style>
.wrapper {
  /*text-transform: uppercase; */
  background: #ececec;
  color: #555;
  cursor: help;
  font-family: "Gill Sans", Impact, sans-serif;
  font-size: 20px;
  position: relative;
  text-align: center;
  width: 200px;
  -webkit-transform: translateZ(0); /* webkit flicker fix */
  -webkit-font-smoothing: antialiased; /* webkit text rendering fix */
}

.wrapper .tooltip {
  white-space: nowrap;
  font-size: 14px;
  text-align: left;
  background: #96b97d;
  bottom: 100%;
  color: #fff;
  display: block;
  left: -25px;
  margin-bottom: 15px;
  opacity: 0;
  padding: 14px;
  pointer-events: none;
  position: absolute;
  
  -webkit-transform: translateY(10px);
     -moz-transform: translateY(10px);
      -ms-transform: translateY(10px);
       -o-transform: translateY(10px);
          transform: translateY(10px);
  -webkit-transition: all .25s ease-out;
     -moz-transition: all .25s ease-out;
      -ms-transition: all .25s ease-out;
       -o-transition: all .25s ease-out;
          transition: all .25s ease-out;
  -webkit-box-shadow: 2px 2px 6px rgba(0, 0, 0, 0.28);
     -moz-box-shadow: 2px 2px 6px rgba(0, 0, 0, 0.28);
      -ms-box-shadow: 2px 2px 6px rgba(0, 0, 0, 0.28);
       -o-box-shadow: 2px 2px 6px rgba(0, 0, 0, 0.28);
          box-shadow: 2px 2px 6px rgba(0, 0, 0, 0.28);
}
.tooltip a {
	color:#fff;
}
/* This bridges the gap so you can mouse into the tooltip without it disappearing */
.wrapper .tooltip:before {
  bottom: -20px;
  content: " ";
  display: block;
  height: 20px;
  left: 0;
  position: absolute;
  width: 100%;
}  

/* CSS Triangles - see Trevor's post */
.wrapper .tooltip:after {
  border-left: solid transparent 10px;
  border-right: solid transparent 10px;
  border-top: solid #96b97d 10px;
  bottom: -10px;
  content: " ";
  height: 0;
  left: 20%;
  margin-left: -13px;
  position: absolute;
  width: 0;
}
.wrapper .tooltip1 {
	margin-left: 50px;
	padding-top: 0px;
}
/*
.wrapper:hover .tooltip {
  opacity: 1;
  pointer-events: auto;
  -webkit-transform: translateY(0px);
     -moz-transform: translateY(0px);
      -ms-transform: translateY(0px);
       -o-transform: translateY(0px);
          transform: translateY(0px);
}
*/
/* IE can just show/hide with no transition */
.lte8 .wrapper .tooltip {
  display: none;
}

.lte8 .wrapper:hover .tooltip {
  display: block;
}

</style>

<link rel="stylesheet" href="../0/upvotejs.css">
<script src=""></script>
<script src=""></script>
<div class="title" id="comments">
	<h2 class="">
    <div class="altblock">
				<i style="font-size:28px;margin-top: 8px;" class="fa fa-plus-square" aria-hidden="true"></i>
		    </div>
    <span class="mw-headline" id="qa_headline">16  篇笔记</span>
	<span class="mw-headline" id="user_add_note" style="float:right;line-height: 62px;padding-right: 14px;"><i class="fa fa-pencil-square-o" aria-hidden="true"></i>  写笔记</span>
    </h2>
</div>

<div id="postcomments"  style="display:none;" >
	<ol class="commentlist">
		<li class="comment even thread-even depth-1" id="comment-17503"><span class="comt-f">#0</span><div class="comt-avatar wrapper"><i style="font-size:36px;" class="fa fa-user-circle" aria-hidden="true"></i><div class="tooltip"><p><i class="fa fa-user" aria-hidden="true"></i>&nbsp;&nbsp;&nbsp;小盟主</p><p><i class="fa fa-envelope" aria-hidden="true"></i>&nbsp;&nbsp;165***0317@qq.com</p></div><div id="runoobvote-id-17503" data-commid = "17503" class="upvotejs"><a class="upvote"></a> <span class="count">226</span></div></div><div class="comt-main" id="div-comment-17503"><p>针对 <span class="marked">__str__</span> 方法给出一个比较直观的例子：</p>

<pre>class people:
    def __init__(self,name,age):
        self.name=name
        self.age=age

    def __str__(self):
        return '这个人的名字是%s,已经有%d岁了！'%(self.name,self.age)

a=people('孙悟空',999)
print(a)</pre>

<p>输出：</p>

<pre>这个人的名字是孙悟空,已经有999岁了！
如果没有重载函数的话输出的就是一串看不懂的字符串：
&lt;__main__.people object at 0x00000272A730D278&gt;</pre><div class="comt-meta wrapper"><span class="comt-author"><a target="_blank" href="javascript:;">小盟主</a><div class="tooltip tooltip1"><p><i class="fa fa-user" aria-hidden="true"></i>&nbsp;&nbsp;&nbsp;小盟主</p><p><i class="fa fa-envelope" aria-hidden="true"></i>&nbsp;&nbsp;165***0317@qq.com</p></div></span>6年前 (2017-09-13)</div></div></li><!-- #comment-## -->
<li class="comment odd alt thread-odd thread-alt depth-1" id="comment-29566"><span class="comt-f">#0</span><div class="comt-avatar wrapper"><i style="font-size:36px;" class="fa fa-user-circle" aria-hidden="true"></i><div class="tooltip"><p><i class="fa fa-user" aria-hidden="true"></i>&nbsp;&nbsp;&nbsp;JasinChen</p><p><i class="fa fa-envelope" aria-hidden="true"></i>&nbsp;&nbsp;402***306@qq.com</p></div><div id="runoobvote-id-29566" data-commid = "29566" class="upvotejs"><a class="upvote"></a> <span class="count">145</span></div></div><div class="comt-main" id="div-comment-29566"><p>最新的 Python3.7 中(2018.07.13)，对类的构造函数进行了精简。</p>

<p>3.7 版本：</p>

<pre>from dataclasses import dataclass
@dataclass
class A:
  x:int
  y:int
  def add(self):
    return self.x + self.y</pre>
<p>相当于以前的：</p>

<pre>class A:
  def __init__(self,x,y):
    self.x = x
    self.y = y
  def add(self):
    return self.x + self.y</pre><div class="comt-meta wrapper"><span class="comt-author"><a target="_blank" href="javascript:;">JasinChen</a><div class="tooltip tooltip1"><p><i class="fa fa-user" aria-hidden="true"></i>&nbsp;&nbsp;&nbsp;JasinChen</p><p><i class="fa fa-envelope" aria-hidden="true"></i>&nbsp;&nbsp;402***306@qq.com</p></div></span>5年前 (2018-07-13)</div></div></li><!-- #comment-## -->
<li class="comment even thread-even depth-1" id="comment-33690"><span class="comt-f">#0</span><div class="comt-avatar wrapper"><i style="font-size:36px;" class="fa fa-user-circle" aria-hidden="true"></i><div class="tooltip"><p><i class="fa fa-user" aria-hidden="true"></i>&nbsp;&nbsp;&nbsp;selfeasy</p><p><i class="fa fa-envelope" aria-hidden="true"></i>&nbsp;&nbsp;ZLT***lfeasy@qq.com</p></div><div id="runoobvote-id-33690" data-commid = "33690" class="upvotejs"><a class="upvote"></a> <span class="count">145</span></div></div><div class="comt-main" id="div-comment-33690"><p data-title="Python3 中类的静态方法、普通方法、类方法"><strong>Python3 中类的静态方法、普通方法、类方法</strong></p>

<p><strong>静态方法</strong>: 用 @staticmethod 装饰的不带 self 参数的方法叫做静态方法，类的静态方法可以没有参数，可以直接使用类名调用。</p>
<p><strong>普通方法</strong>: 默认有个self参数，且只能被对象调用。</p>
<p><strong>类方法</strong>: 默认有个 cls 参数，可以被类和对象调用，需要加上 @classmethod 装饰器。</p>

<pre>class Classname:
    @staticmethod
    def fun():
        print('静态方法')

    @classmethod
    def a(cls):
        print('类方法')

    # 普通方法
    def b(self):
        print('普通方法')



Classname.fun()
Classname.a()

C = Classname()
C.fun()
C.a()
C.b()</pre><div class="comt-meta wrapper"><span class="comt-author"><a target="_blank" href="../note/33690">selfeasy</a><div class="tooltip tooltip1"><p><i class="fa fa-user" aria-hidden="true"></i>&nbsp;&nbsp;&nbsp;selfeasy</p><p><i class="fa fa-envelope" aria-hidden="true"></i>&nbsp;&nbsp;ZLT***lfeasy@qq.com</p></div></span>5年前 (2018-08-07)</div></div></li><!-- #comment-## -->
<li class="comment odd alt thread-odd thread-alt depth-1" id="comment-34572"><span class="comt-f">#0</span><div class="comt-avatar wrapper"><i style="font-size:36px;" class="fa fa-user-circle" aria-hidden="true"></i><div class="tooltip"><p><i class="fa fa-user" aria-hidden="true"></i>&nbsp;&nbsp;&nbsp;chise</p><p><i class="fa fa-envelope" aria-hidden="true"></i>&nbsp;&nbsp;531***371@qq.com</p></div><div id="runoobvote-id-34572" data-commid = "34572" class="upvotejs"><a class="upvote"></a> <span class="count">38</span></div></div><div class="comt-main" id="div-comment-34572"><p>反向运算符重载：</p><ul><li>__radd__:&nbsp;加运算</li><li>__rsub__:&nbsp;减运算</li><li>__rmul__:&nbsp;乘运算</li><li>__rdiv__:&nbsp;除运算</li><li>__rmod__:&nbsp;求余运算</li><li>__rpow__:&nbsp;乘方</li></ul><p>复合重载运算符：</p><ul><li>__iadd__:&nbsp;加运算</li><li>__isub__:&nbsp;减运算</li><li>__imul__:&nbsp;乘运算</li><li>__idiv__:&nbsp;除运算</li><li>__imod__:&nbsp;求余运算</li><li>__ipow__:&nbsp;乘方</li></ul><p>运算符重载的时候：</p>
<pre>#!/usr/bin/python3

class Vector:
    def __init__(self, a, b):
        self.a = a
        self.b = b
    def __str__(self):
        return 'Vector (%d, %d)' % (self.a, self.b)

    def __repr__(self):
        return 'Vector (%d, %d)' % (self.a, self.b)

    def __add__(self,other):
        if other.__class__ is Vector:
            return Vector(self.a + other.a, self.b + other.b)
        elif other.__class__ is int:
            return Vector(self.a+other,self.b)

    def __radd__(self,other):
        """反向算术运算符的重载
        __add__运算符重载可以保证V+int的情况下不会报错，但是反过来int+V就会报错，通过反向运算符重载可以解决此问题
        """

        if other.__class__ is int or other.__class__ is float:
            return Vector(self.a+other,self.b)
        else:
            raise ValueError("值错误")

    def __iadd__(self,other):
        """复合赋值算数运算符的重载
        主要用于列表，例如L1+=L2,默认情况下调用__add__，会生成一个新的列表，
        当数据过大的时候会影响效率，而此函数可以重载+=，使L2直接增加到L1后面
        """

        if other.__class__ is Vector:
            return Vector(self.a + other.a, self.b + other.b)
        elif other.__class__ is int:
            return Vector(self.a+other,self.b)
v1 = Vector(2,10)
v2 = Vector(5,-2)
print (v1 + v2)
print (v1+5)
print (6+v2)</pre><div class="comt-meta wrapper"><span class="comt-author"><a target="_blank" href="javascript:;">chise</a><div class="tooltip tooltip1"><p><i class="fa fa-user" aria-hidden="true"></i>&nbsp;&nbsp;&nbsp;chise</p><p><i class="fa fa-envelope" aria-hidden="true"></i>&nbsp;&nbsp;531***371@qq.com</p></div></span>5年前 (2018-08-30)</div></div></li><!-- #comment-## -->
<li class="comment byuser comment-author-tianqixin bypostauthor even thread-even depth-1" id="comment-37305"><span class="comt-f">#0</span><div class="comt-avatar wrapper"><i style="font-size:36px;" class="fa fa-user-circle" aria-hidden="true"></i><div class="tooltip"><p><i class="fa fa-user" aria-hidden="true"></i>&nbsp;&nbsp;&nbsp;FS</p><p><i class="fa fa-envelope" aria-hidden="true"></i>&nbsp;&nbsp;429***f0967@qq.com</p></div><div id="runoobvote-id-37305" data-commid = "37305" class="upvotejs"><a class="upvote"></a> <span class="count">555</span></div></div><div class="comt-main" id="div-comment-37305"><p><img src="//www.runoob.com/wp-content/uploads/2013/12/oopxxx.png"></p><div class="comt-meta wrapper"><span class="comt-author"><a target="_blank" href="javascript:;">FS</a><div class="tooltip tooltip1"><p><i class="fa fa-user" aria-hidden="true"></i>&nbsp;&nbsp;&nbsp;FS</p><p><i class="fa fa-envelope" aria-hidden="true"></i>&nbsp;&nbsp;429***f0967@qq.com</p></div></span>4年前 (2018-11-22)</div></div></li><!-- #comment-## -->
<li class="comment odd alt thread-odd thread-alt depth-1" id="comment-39287"><span class="comt-f">#0</span><div class="comt-avatar wrapper"><i style="font-size:36px;" class="fa fa-user-circle" aria-hidden="true"></i><div class="tooltip"><p><i class="fa fa-user" aria-hidden="true"></i>&nbsp;&nbsp;&nbsp;像是一个菜鸟</p><p><i class="fa fa-envelope" aria-hidden="true"></i>&nbsp;&nbsp;141***0013@qq.com</p></div><div id="runoobvote-id-39287" data-commid = "39287" class="upvotejs"><a class="upvote"></a> <span class="count">119</span></div></div><div class="comt-main" id="div-comment-39287">    
<p data-title="Python __name__"><strong>关于 __name__</strong></p>

<p>首先需要了解 __name__ 是属于 python 中的内置类属性，就是它会天生就存在于一个 python 程序中，代表对应程序名称。</p>

<p>比如所示的一段代码里面（这个脚本命名为 pcRequests.py），我只设了一个函数，但是并没有地方运行它，所以当 run 了这一段代码之后我们有会发现这个函数并没有被调用。但是当我们在运行这个代码时这个代码的 __name__ 的值为 __main__ （一段程序作为主线运行程序时其内置名称就是 __main__）。</p>

<pre>import requests
class requests(object):
    def __init__(self,url):
        self.url=url
        self.result=self.getHTMLText(self.url)
    def getHTMLText(url):
        try:
            r=requests.get(url,timeout=30)
            r.raise_for_status()
            r.encoding=r.apparent_encoding
            return r.text
        except:
            return "This is a error."
print(__name__)</pre>
<p>结果：</p>

<pre>__main__
Process finished with exit code 0</pre>

<p>当这个 pcRequests.py 作为模块被调用时，则它的 __name__ 就是它自己的名字：</p>

<pre>import pcRequestspcRequestsc=pcRequestsc.__name__</pre>

<p>结果：</p>

<pre>'pcRequests'</pre>

<p>看到这里应该能明白，自己的 __name__ 在自己用时就是 main，当自己作为模块被调用时就是自己的名字，就相当于：<strong>我管自己叫我自己，但是在朋友眼里我就是小仙女一样</strong>。</p><div class="comt-meta wrapper"><span class="comt-author"><a target="_blank" href="../note/39287">像是一个菜鸟</a><div class="tooltip tooltip1"><p><i class="fa fa-user" aria-hidden="true"></i>&nbsp;&nbsp;&nbsp;像是一个菜鸟</p><p><i class="fa fa-envelope" aria-hidden="true"></i>&nbsp;&nbsp;141***0013@qq.com</p></div></span>4年前 (2019-01-24)</div></div></li><!-- #comment-## -->
<li class="comment even thread-even depth-1" id="comment-42704"><span class="comt-f">#0</span><div class="comt-avatar wrapper"><i style="font-size:36px;" class="fa fa-user-circle" aria-hidden="true"></i><div class="tooltip"><p><i class="fa fa-user" aria-hidden="true"></i>&nbsp;&nbsp;&nbsp;laoshi</p><p><i class="fa fa-envelope" aria-hidden="true"></i>&nbsp;&nbsp;lao***@ee.com</p></div><div id="runoobvote-id-42704" data-commid = "42704" class="upvotejs"><a class="upvote"></a> <span class="count">41</span></div></div><div class="comt-main" id="div-comment-42704"><p><strong data-title>Python3 类方法总结</strong></p>
<ul><li>
普通方法：对象访问</li><li>
私有方法：两个下划线开头，只能在类内部访问</li><li>
静态方法：类和对象访问，不能和其他方法重名，不然会相互覆盖，后面定义的会覆盖前面的</li><li>
类方法：类和对象访问，不能和其他方法重名，不然会相互覆盖，后面定义的会覆盖前面的</li><li>
多继承情况下：从左到右查找方法，找到为止，不然就抛出异常</li></ul>


<pre>class People:

    # 定义基本属性
    name=''
    age=0
    # 定义私有属性外部无法直接访问
    __weight=0
    def __init__(self,n,a,w):
        self.name = n
        self.age = a
        self.__weight = w
    def speak(self):
        print("%s say : i am %d."%(self.name,self.age))
p = People('Python',10,20)
p.speak()
# __weight无法直接访问
print(p.name,'--',p.age)#,'--',p.__weight)</pre>

<p><strong>继承</strong></p>

<p>单继承:</p>

<pre>class Student(People):
    grade=''
    def __init__(self,n,a,w,g):
        People.__init__(self,n,a,w)
        self.grade = g

    # 覆写父类方法
    def speak():
        print("%s 说: 我 %d 岁了，我在读 %d 年级"%(self.name,self.age,self.grade))

class Speak():
    topic=''
    name=''
    def __init__(self,n,t):
        self.name = n
        self.topic = t
    # 普通方法，对象调用
    def speak(self):
        print("我叫 %s，我是一个演说家，我演讲的主题是 %s"%(self.name,self.topic))

    # 私有方法，self调用
    def __song(self):
        print('唱一首歌自己听',self);

    # 静态方法，对象和类调用，不能和其他方法重名，不然会相互覆盖，后面定义的会覆盖前面的
    @staticmethod
    def song():
        print('唱一首歌给类听:静态方法');

    # 普通方法，对象调用
    def song(self):
        print('唱一首歌给你们听',self);
        
    # 类方法，对象和类调用，不能和其他方法重名，不然会相互覆盖，后面定义的会覆盖前面的
    @classmethod
    def song(self):
        print('唱一首歌给类听:类方法',self)</pre>

<p>多继承:</p>

<pre>class Sample(Speak,Student):
    a = ''
    def __init__(self,n,a,w,g,t):
        Student.__init__(self,n,a,w,g)
        Speak.__init__(self,n,t)
test = Sample('Song',24,56,7,'Python')
test.speak()
test.song()
Sample.song()
Sample.song()
test.song()

# test.__song() 无法访问私有方法</pre><div class="comt-meta wrapper"><span class="comt-author"><a target="_blank" href="../note/42704">laoshi</a><div class="tooltip tooltip1"><p><i class="fa fa-user" aria-hidden="true"></i>&nbsp;&nbsp;&nbsp;laoshi</p><p><i class="fa fa-envelope" aria-hidden="true"></i>&nbsp;&nbsp;lao***@ee.com</p></div></span>4年前 (2019-05-13)</div></div></li><!-- #comment-## -->
<li class="comment odd alt thread-odd thread-alt depth-1" id="comment-43812"><span class="comt-f">#0</span><div class="comt-avatar wrapper"><i style="font-size:36px;" class="fa fa-user-circle" aria-hidden="true"></i><div class="tooltip"><p><i class="fa fa-user" aria-hidden="true"></i>&nbsp;&nbsp;&nbsp;徙徒</p><p><i class="fa fa-envelope" aria-hidden="true"></i>&nbsp;&nbsp;143***2467@qq.com</p></div><div id="runoobvote-id-43812" data-commid = "43812" class="upvotejs"><a class="upvote"></a> <span class="count">35</span></div></div><div class="comt-main" id="div-comment-43812"><p>所有专有方法中，__init__()要求无返回值，或者返回 None。而其他方法，如__str__()、__add__()等，一般都是要返回值的，如下所示：</p>

<pre>&gt;&gt;&gt; class Complex:
...     def __init__(self, realpart, imagpart):
...         self.r = realpart
...         self.i = imagpart
...         return 'hello'
...
&gt;&gt;&gt; x = Complex(3.0, -4.5)
Traceback (most recent call last):
  File "&lt;stdin&gt;", line 1, in &lt;module&gt;
TypeError: __init__() should return None, not 'str'</pre>

<p>而对于 __str__()、__add__() 等。</p>

<pre>def __str__(self):
        return 'Vector (%d, %d)' % (self.a, self.b)

def __repr__(self):
    return 'Vector (%d, %d)' % (self.a, self.b)

def __add__(self,other):
    if other.__class__ is Vector:
        return Vector(self.a + other.a, self.b + other.b)
    elif other.__class__ is int:
        return Vector(self.a+other,self.b)</pre><div class="comt-meta wrapper"><span class="comt-author"><a target="_blank" href="javascript:;">徙徒</a><div class="tooltip tooltip1"><p><i class="fa fa-user" aria-hidden="true"></i>&nbsp;&nbsp;&nbsp;徙徒</p><p><i class="fa fa-envelope" aria-hidden="true"></i>&nbsp;&nbsp;143***2467@qq.com</p></div></span>4年前 (2019-06-20)</div></div></li><!-- #comment-## -->
<li class="comment even thread-even depth-1" id="comment-43813"><span class="comt-f">#0</span><div class="comt-avatar wrapper"><i style="font-size:36px;" class="fa fa-user-circle" aria-hidden="true"></i><div class="tooltip"><p><i class="fa fa-user" aria-hidden="true"></i>&nbsp;&nbsp;&nbsp;徙徒</p><p><i class="fa fa-envelope" aria-hidden="true"></i>&nbsp;&nbsp;143***2467@qq.com</p></div><div id="runoobvote-id-43813" data-commid = "43813" class="upvotejs"><a class="upvote"></a> <span class="count">33</span></div></div><div class="comt-main" id="div-comment-43813"><p>类的专有方法中，也是存在默认优先级的，多个方法都有返回值，但一般优先取 __str__() 的返回值，如下面例子：</p>

类的专有方法中，也是存在默认优先级的，多个方法都有返回值，但一般优先取 __str__() 的返回值，如下面例子：

<pre>class Vector:
    def __init__(self, a, b):
        self.a = a
        self.b = b
    def __repr__(self):
        return 'Vector (%d, %d)' % (self.b, self.a)
    def __str__(self):
        return 'Vector (%d, %d)' % (self.a, self.b)
    def __add__(self,other):
        return Vector(self.a + other.a, self.b + other.b)

v1 = Vector(2,10)
print (v1)</pre>

<p>结果是 Vector(2,10)，而不是 Vector(10,2)。这里优先使用 __str__() 的返回值。</p>

<pre>v1.__repr__()</pre>

<p>结果是：<strong>Vector(10,2)</strong></p><div class="comt-meta wrapper"><span class="comt-author"><a target="_blank" href="javascript:;">徙徒</a><div class="tooltip tooltip1"><p><i class="fa fa-user" aria-hidden="true"></i>&nbsp;&nbsp;&nbsp;徙徒</p><p><i class="fa fa-envelope" aria-hidden="true"></i>&nbsp;&nbsp;143***2467@qq.com</p></div></span>4年前 (2019-06-20)</div></div></li><!-- #comment-## -->
<li class="comment odd alt thread-odd thread-alt depth-1" id="comment-43814"><span class="comt-f">#0</span><div class="comt-avatar wrapper"><i style="font-size:36px;" class="fa fa-user-circle" aria-hidden="true"></i><div class="tooltip"><p><i class="fa fa-user" aria-hidden="true"></i>&nbsp;&nbsp;&nbsp;徙徒</p><p><i class="fa fa-envelope" aria-hidden="true"></i>&nbsp;&nbsp;143***2467@qq.com</p></div><div id="runoobvote-id-43814" data-commid = "43814" class="upvotejs"><a class="upvote"></a> <span class="count">152</span></div></div><div class="comt-main" id="div-comment-43814"><p>笔记中有位同学如下这样写道，但我认为不准确：</p>

<p><strong>最新的 Python3.7 中(2018.07.13)，对类的构造函数进行了精简。</strong></p>

<p>3.7 版本：</p>

<pre>from dataclasses import dataclass
@dataclass
class A:
  x:int
  y:int
  def add(self):
    return self.x + self.y</pre>
<p>相当于以前的：</p>

<pre>class B:
  def __init__(self,x,y):
    self.x = x
    self.y = y
  def add(self):
    return self.x + self.y</pre>
<p>实际上，对于类 A， 实例化时不需要参数；而对于类 B，实例化时需要输入 (x, y) 参数，这才是两者的核心区别。定义类时，若需要输入参数，则一般必须使用 __init__()方法；若不需要输入参数，是否使用 __init__() 方法都可以。</p>
<p>
和版本是否对类的构造函数进行了精简，关系不大。</p><div class="comt-meta wrapper"><span class="comt-author"><a target="_blank" href="javascript:;">徙徒</a><div class="tooltip tooltip1"><p><i class="fa fa-user" aria-hidden="true"></i>&nbsp;&nbsp;&nbsp;徙徒</p><p><i class="fa fa-envelope" aria-hidden="true"></i>&nbsp;&nbsp;143***2467@qq.com</p></div></span>4年前 (2019-06-20)</div></div></li><!-- #comment-## -->
<li class="comment even thread-even depth-1" id="comment-43815"><span class="comt-f">#0</span><div class="comt-avatar wrapper"><i style="font-size:36px;" class="fa fa-user-circle" aria-hidden="true"></i><div class="tooltip"><p><i class="fa fa-user" aria-hidden="true"></i>&nbsp;&nbsp;&nbsp;徙徒</p><p><i class="fa fa-envelope" aria-hidden="true"></i>&nbsp;&nbsp;143***2467@qq.com</p></div><div id="runoobvote-id-43815" data-commid = "43815" class="upvotejs"><a class="upvote"></a> <span class="count">34</span></div></div><div class="comt-main" id="div-comment-43815"><p>在 Python 中，方法分为三类实例方法、类方法、静态方法。三者区别看代码如下：</p>

<pre>class Test(object):
    def InstanceFun(self):
        print("InstanceFun");
        print(self);
    @classmethod
    def ClassFun(cls):
        print("ClassFun");
        print(cls);
    @staticmethod
    def StaticFun():
        print("StaticFun");

t = Test();　　　　　
t.InstanceFun();　　　# 输出InstanceFun，打印对象内存地址&ldquo;&lt;__main__.Test object at 0x0293DCF0&gt;&rdquo;
Test.ClassFun();     # 输出ClassFun，打印类位置 &lt;class '__main__.Test'&gt;
Test.StaticFun();    # 输出StaticFun
t.StaticFun();       # 输出StaticFun
t.ClassFun();        # 输出ClassFun，打印类位置 &lt;class '__main__.Test'&gt;
Test.InstanceFun();     # 错误，TypeError: unbound method instanceFun() must be called with Test instance as first argument
Test.InstanceFun(t);    # 输出InstanceFun，打印对象内存地址&ldquo;&lt;__main__.Test object at 0x0293DCF0&gt;&rdquo;
t.ClassFun(Test);       # 错误   classFun() takes exactly 1 argument (2 given)   </pre>

<p>可以看到，在 Python 中，两种方法的主要区别在于参数。实例方法隐含的参数为类实例 self，而类方法隐含的参数为类本身 cls。</p>

<p>静态方法无隐含参数，主要为了类实例也可以直接调用静态方法。</p>

<p>所以逻辑上类方法应当只被类调用，实例方法实例调用，静态方法两者都能调用。主要区别在于参数传递上的区别，实例方法悄悄传递的是self引用作为参数，而类方法悄悄传递的是 cls 引用作为参数。</p>

<p>Python 实现了一定的灵活性使得类方法和静态方法，都能够被实例和类二者调用。</p><div class="comt-meta wrapper"><span class="comt-author"><a target="_blank" href="javascript:;">徙徒</a><div class="tooltip tooltip1"><p><i class="fa fa-user" aria-hidden="true"></i>&nbsp;&nbsp;&nbsp;徙徒</p><p><i class="fa fa-envelope" aria-hidden="true"></i>&nbsp;&nbsp;143***2467@qq.com</p></div></span>4年前 (2019-06-20)</div></div></li><!-- #comment-## -->
<li class="comment odd alt thread-odd thread-alt depth-1" id="comment-45306"><span class="comt-f">#0</span><div class="comt-avatar wrapper"><i style="font-size:36px;" class="fa fa-user-circle" aria-hidden="true"></i><div class="tooltip"><p><i class="fa fa-user" aria-hidden="true"></i>&nbsp;&nbsp;&nbsp;兔子</p><p><i class="fa fa-envelope" aria-hidden="true"></i>&nbsp;&nbsp;8bi***gmail.com</p></div><div id="runoobvote-id-45306" data-commid = "45306" class="upvotejs"><a class="upvote"></a> <span class="count">30</span></div></div><div class="comt-main" id="div-comment-45306"><p>类的二元方法运算符重载介绍的并不全面，文中介绍的全是正向方法，其实还有反向方法，就地方法。下面补充一些。</p>

<p>当解释器碰到 a+b 时，会做以下事情：</p>

<p>从 a 类中找 __add__ 若返回值不是 NotImplemented, 则调用 <strong>a.__add__(b)</strong>。</p>
<p>若 a 类中没有 __add__ 方法，则检查 b 有没有 __radd__ 。如果如果有，则调用 b.__radd__(a)，若没有，则返回 NotImplemented。</p>
<p>接上条，若 b 也没有 __radd__  方法，则抛出 TypeError，在错误消息中知名操作数类型不支持。</p>
<p>比如：向量类 &lt;Myvector&gt; 应当有向量与整数的乘法:</p>

<pre>&gt;&gt;&gt;a = Myvector([1,2,3])
&gt;&gt;&gt;print(a.value)
[1,2,3]
&gt;&gt;&gt;b=3
&gt;&gt;&gt;c = a*b   #此时调用Myvector.__mul__()
&gt;&gt;&gt;print(c.value)
[3,6,9]
&gt;&gt;&gt; d=b*a  #这句会出错。</pre>

<p>期望得到 <strong>b*a</strong> 也返回一个向量，b*a 应该等于 a*b。此时就需要在 Myvector 类中定义一个__rmul__方法。</p>


<pre>def __rmul__(self, other):
    if isinstance(other, int):
        return Myvector([a*other for a in self.m])
</pre>

<p>每个运算符都有正向方法重载，反向方法重载。有一些有就地方法（即不返回新的对象，而是修改原本对象）。</p><div class="comt-meta wrapper"><span class="comt-author"><a target="_blank" href="javascript:;">兔子</a><div class="tooltip tooltip1"><p><i class="fa fa-user" aria-hidden="true"></i>&nbsp;&nbsp;&nbsp;兔子</p><p><i class="fa fa-envelope" aria-hidden="true"></i>&nbsp;&nbsp;8bi***gmail.com</p></div></span>4年前 (2019-08-02)</div></div></li><!-- #comment-## -->
<li class="comment even thread-even depth-1" id="comment-46213"><span class="comt-f">#0</span><div class="comt-avatar wrapper"><i style="font-size:36px;" class="fa fa-user-circle" aria-hidden="true"></i><div class="tooltip"><p><i class="fa fa-user" aria-hidden="true"></i>&nbsp;&nbsp;&nbsp;shunhwa</p><p><i class="fa fa-envelope" aria-hidden="true"></i>&nbsp;&nbsp;hex***ua617@sina.com</p></div><div id="runoobvote-id-46213" data-commid = "46213" class="upvotejs"><a class="upvote"></a> <span class="count">46</span></div></div><div class="comt-main" id="div-comment-46213"><p><strong>__str__函数</strong></p>
<p><span class="marked">__str__</span> 是一个类的方法，在打印类对象，获取其属性信息时调用。打印一个实例化对象时，默认打印的其实时一个对象的地址，但是我们可以对其进行重载，打印我们想要的信息。例如上面的例子中进行的重载。</p><div class="comt-meta wrapper"><span class="comt-author"><a target="_blank" href="javascript:;">shunhwa</a><div class="tooltip tooltip1"><p><i class="fa fa-user" aria-hidden="true"></i>&nbsp;&nbsp;&nbsp;shunhwa</p><p><i class="fa fa-envelope" aria-hidden="true"></i>&nbsp;&nbsp;hex***ua617@sina.com</p></div></span>4年前 (2019-08-28)</div></div></li><!-- #comment-## -->
<li class="comment odd alt thread-odd thread-alt depth-1" id="comment-50593"><span class="comt-f">#0</span><div class="comt-avatar wrapper"><i style="font-size:36px;" class="fa fa-user-circle" aria-hidden="true"></i><div class="tooltip"><p><i class="fa fa-user" aria-hidden="true"></i>&nbsp;&nbsp;&nbsp;小叶Little_Ye</p><p><i class="fa fa-envelope" aria-hidden="true"></i>&nbsp;&nbsp;lit***ye233@foxmail.com</p></div><div id="runoobvote-id-50593" data-commid = "50593" class="upvotejs"><a class="upvote"></a> <span class="count">18</span></div></div><div class="comt-main" id="div-comment-50593"><p>在类的方法中直接修改 self 是无效操作，即使 self 变量的地址与实例地址相同：</p>

<pre>class C:
  def __init__(self, a):
    self.a = a
  def construct(self, a):
    c = C(a)
    self = c
  def getid(self):
    return id(self)

if __name__ == '__main__':
  c1 = C(2)
  c1.construct(3) # c1.a == 2
  print(id(c1) == c1.getid()) # True</pre><div class="comt-meta wrapper"><span class="comt-author"><a target="_blank" href="javascript:;">小叶Little_Ye</a><div class="tooltip tooltip1"><p><i class="fa fa-user" aria-hidden="true"></i>&nbsp;&nbsp;&nbsp;小叶Little_Ye</p><p><i class="fa fa-envelope" aria-hidden="true"></i>&nbsp;&nbsp;lit***ye233@foxmail.com</p></div></span>3年前 (2020-02-11)</div></div></li><!-- #comment-## -->
<li class="comment even thread-even depth-1" id="comment-52965"><span class="comt-f">#0</span><div class="comt-avatar wrapper"><i style="font-size:36px;" class="fa fa-user-circle" aria-hidden="true"></i><div class="tooltip"><p><i class="fa fa-user" aria-hidden="true"></i>&nbsp;&nbsp;&nbsp;日日夜夜</p><p><i class="fa fa-envelope" aria-hidden="true"></i>&nbsp;&nbsp;dwl***t30@gmail.com</p></div><div id="runoobvote-id-52965" data-commid = "52965" class="upvotejs"><a class="upvote"></a> <span class="count">78</span></div></div><div class="comt-main" id="div-comment-52965"><p>事实上 class 的私有属性在外部也是可以访问的我们可以看下文中的例子。</p>

<pre>#!/usr/bin/python3
class People:
    def __init__(self, name, age, ):
        self.name = name
        self.age = age
        self.__privater_var = 10  
  
    def intro(self):
        print(f'My name is {self.name},I\'m {self.age}')

    def get_var(self):
        print(self.__privater_var)

    def set_var(self, var):
        self.__privater_var = var

someone = People(name='jack', age=20)
someone.intro()
print(someone.age)
someone.get_var() # 通过get_var方法访问私有属性__privater_var，值为10
someone.set_var(30) # 通过set_var方法修改私有属性__privater_var，值为30
someone.get_var() # 再次通过get_var方法访问私有属性__privater_var，值为30</pre>
<p>结果：</p>

<pre>My name is jack,I'm 20
20
10
30</pre><p>
接下下来看看为什么我们使用someone.__privater_var会报错呢？</p>

<pre>AttributeError: 'People' object has no attribute '__privater_var'</pre>
<p>这里我们先使用 dir() 函数：</p>

<pre>print(dir(someone)) #  获得当前someone的属性列表</pre>
<p>结果：</p>

<pre>['_People__privater_var', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'age', 'get_var', 'intro', 'name', 'set_var']</pre><p>
从打印出的结果中，我们并没有找到'_peivater_var'但是我们看到一个'_People__privater_var'.有没有想到什么？原来是被重命名了。好，我们来试试：</p>

<pre>print(someone._People__privater_var)
someone._People__privater_var = 40
print(someone._People__privater_var)</pre>
<p>结果：</p>
<pre>
30
40</pre><p>
所以说，私有变量的属性是可以修改的。既然Python阻止访问，一般情况下就不要访问。</p><div class="comt-meta wrapper"><span class="comt-author"><a target="_blank" href="javascript:;">日日夜夜</a><div class="tooltip tooltip1"><p><i class="fa fa-user" aria-hidden="true"></i>&nbsp;&nbsp;&nbsp;日日夜夜</p><p><i class="fa fa-envelope" aria-hidden="true"></i>&nbsp;&nbsp;dwl***t30@gmail.com</p></div></span>3年前 (2020-04-23)</div></div></li><!-- #comment-## -->
<li class="comment odd alt thread-odd thread-alt depth-1" id="comment-73991"><span class="comt-f">#0</span><div class="comt-avatar wrapper"><i style="font-size:36px;" class="fa fa-user-circle" aria-hidden="true"></i><div class="tooltip"><p><i class="fa fa-user" aria-hidden="true"></i>&nbsp;&nbsp;&nbsp;真心</p><p><i class="fa fa-envelope" aria-hidden="true"></i>&nbsp;&nbsp;297***2808@qq.com</p></div><div id="runoobvote-id-73991" data-commid = "73991" class="upvotejs"><a class="upvote"></a> <span class="count">30</span></div></div><div class="comt-main" id="div-comment-73991"><p>上面给的 people 类定义混淆了类属性与实例属性，下面我给出自己改写的 People 定义予以证明:</p>

<pre># 类定义
class People:    
    name = 'nnnnnn'  #这个是类属性    
    age = 20         #这个也是类属性    
    __weight = 21    #这个也是类属性，且是私有的    
    # 定义构造方法    
    def __init__(self, name, age, weight):        
        self.name = name    #这里改写的是实例属性，与类属性没有关联        
        self.age = age     #这里改写的是实例属性，与类属性没有关联        
        self.__weight = weight  #实例属性, 这里改写的是实例属性，与类属性没有关联        
        #People.__weight = weight    
    def speak(self):        
        print("说: 我叫 {0}，{1} 岁，体重{2}斤（实例属性）" .format(self.name, self.age, self.__weight))    
    def speak2(self):        
        print("私有类属性__weight = {0}".format(People.__weight))

p1 = People('张三', 10, 60)
p1.speak()
p1.speak2()
print("类属性：name={0}, age={1}".format(People.name, People.age))

p2 = People('李四', 12, 69)
p2.speak()
p2.speak2()
print("类属性：name={0}, age={1}".format(People.name, People.age))</pre>
<p>运行结果：</p>

<pre>说: 我叫 张三，10 岁，体重60斤（实例属性）
私有类属性__weight = 21
类属性：name=nnnnnn, age=20
说: 我叫 李四，12 岁，体重69斤（实例属性）
私有类属性__weight = 21
类属性：name=nnnnnn, age=20</pre><div class="comt-meta wrapper"><span class="comt-author"><a target="_blank" href="javascript:;">真心</a><div class="tooltip tooltip1"><p><i class="fa fa-user" aria-hidden="true"></i>&nbsp;&nbsp;&nbsp;真心</p><p><i class="fa fa-envelope" aria-hidden="true"></i>&nbsp;&nbsp;297***2808@qq.com</p></div></span>9个月前 (07-17)</div></div></li><!-- #comment-## -->
	</ol>
	<div class="pagenav">
			</div>
</div>
<div id="respond" class="no_webshot"> 
		<div class="comment-signarea" style="display:none; padding: 20px 20px;"> 
	<h3 class="text-muted" id="share_code" style="color: #799961;"><i class="fa fa-pencil-square-o" aria-hidden="true"></i> 点我分享笔记</h3>
	<!--
	<p style="font-size:14px;">笔记需要是本篇文章的内容扩展！</p><br>
	<p style="font-size:12px;"><a href="../tougao" target="_blank">文章投稿，可点击这里</a></p>
	<p style="font-size:14px;"><a href="../w3cnote/runoob-user-test-intro.html#invite" target="_blank">注册邀请码获取方式</a></p>
		<h3 class="text-muted"><i class="fa fa-info-circle" aria-hidden="true"></i> 分享笔记前必须<a href="javascript:;" class="runoob-pop">登录</a>！</h3>
		<p><a href="../w3cnote/runoob-user-test-intro.html#invite" target="_blank">注册邀请码获取方式</a></p>-->
	</div>
		
	<form action="/wp-content/themes/runoob/option/addnote.php" method="post" id="commentform" style="display:none;">
		<div class="comt">
			<div class="comt-title">
				<i style="font-size:36px;" class="fa fa-user-circle" aria-hidden="true"></i>				<p><a id="cancel-comment-reply-link" href="javascript:;">取消</a></p>
			</div>
			<div class="comt-box">
			<div id="mded"></div>
			
				<div class="comt-ctrl">
					<div class="comt-tips"><input type='hidden' name='comment_post_ID' value='7507' id='comment_post_ID' />
<input type='hidden' name='comment_parent' id='comment_parent' value='0' />
</div>
					<button type="submit" name="submit" id="submit" tabindex="5"><i class="fa fa-pencil" aria-hidden="true"></i> 分享笔记</button>
				</div>
			</div>
		
				
					<div class="comt-comterinfo"> 
						<ul id="comment-author-info">
							<li class="form-inline"><label class="hide" for="author">昵称</label><input class="ipt" type="text" name="author" id="author" value="" tabindex="2" placeholder="昵称"><span class="text-muted">昵称 (必填)</span></li>
							<li class="form-inline"><label class="hide" for="email">邮箱</label><input class="ipt" type="text" name="email" id="email" value="" tabindex="3" placeholder="邮箱"><span class="text-muted">邮箱 (必填)</span></li>
							<li class="form-inline"><label class="hide" for="url">引用地址</label><input class="ipt" type="text" name="url" id="url" value="" tabindex="4" placeholder="引用地址"><span class="text-muted">引用地址</span></li>
						</ul>
					</div>
				
			
		</div>

	</form>
	</div>
<script type="text/javascript">
$(function() {
	//初始化编辑器
	
	var editor = new Simditor({
	  textarea: $('#mded'),
	  placeholder: '写笔记...',
	  upload:false,
	 // upload: {url:'/api/comment_upload_file.php',params: null,fileKey: 'upload_file',connectionCount: 1,leaveConfirm: '文件正在上传，您确定离开?'},
	  defaultImage: 'https://www.runoob.com/images/logo.png',
	  codeLanguages: '',
	  autosave: 'editor-content',
	  toolbar: [  'bold','code','ul','ol','image' ]
	});
	editor.on('selectionchanged', function() {
		$(".code-popover").hide();
	});

	// 提交数据
	$("#share_code").click(function() {
		$(".comment-signarea").hide();
		$("#commentform").show();
		
	});
	$("#user_add_note").click(function() {
		$(".comment-signarea").hide();
		$("#commentform").show();
		$('html, body').animate({
       	    scrollTop: $("#respond").offset().top
    	}, 200);
	});

	// 提交笔记
	var commentform=$('#commentform');
	commentform.prepend('<div id="comment-status" style="display:none;" ></div>');
	var statusdiv=$('#comment-status');
	
	commentform.submit(function(e){
		e.preventDefault();
		var noteContent = editor.getValue();
		// console.log(noteContent);
		noteContent = noteContent.replace(/<pre><code>/g,"<pre>");
		noteContent = noteContent.replace(/<\/code><\/pre>/g,"</pre>");
		
		// 系列化表单数据
		var comment_parent = 0;
		var is_user_logged_in = $("#is_user_logged_in").val();
		var comment_post_ID =  7507;
		var _wp_unfiltered_html_comment = $("#_wp_unfiltered_html_comment").val();
		var comment = noteContent;
		var author = $("#author").val();
		var url = $("#url").val();
		var email = $("#email").val();
		if(isBlank(author) && is_user_logged_in==0) {
			statusdiv.html('<p  class="ajax-error">请输入昵称！</p>').show();
		} else if(isBlank(email)  && is_user_logged_in==0) {
			statusdiv.html('<p  class="ajax-error">请输入邮箱！</p>').show();
		} else {
			// var formdata=commentform.serialize() + "&comment=" + noteContent ;
			// 添加状态信息
			statusdiv.html('<p>Processing...</p>').show();
			// 获取表单提交地址
			var formurl=commentform.attr('action');
			
			// 异步提交
			$.ajax({
					type: 'post',
					url: formurl,
					dataType:'json',
					data: {"comment_parent":comment_parent,"comment_post_ID":comment_post_ID, "_wp_unfiltered_html_comment":_wp_unfiltered_html_comment,"comment":comment,"url":url, "email":email,"author":author},
					error: function(XMLHttpRequest, textStatus, errorThrown){
					statusdiv.html('<p class="ajax-error" >数据不完整或表单提交太快了！</p>').show();
				},
				success: function(data, textStatus){
					if(data.errorno=="0") {
						$("#submit").prop('disabled', true);
						statusdiv.html('<p class="ajax-success" >笔记已提交审核，感谢分享笔记！</p>').show();
						alert('笔记已提交审核，感谢分享笔记！');
					}else{
						statusdiv.html('<p class="ajax-error" >'+data.msg+'</p>').show();
					}
					commentform.find('textarea[name=comment]').val('');
				}
			});
			setTimeout(function(){
		        $("#submit").prop('disabled', false);
		    }, 10*1000);
		}
		return false;

	});
	$(".comt-author").click(function() {
		href = $(this).children("a").attr("href");
		if(href.indexOf("/note/")!=-1) {
			var win = window.open(href, '_blank');
  			win.focus();
		}
	});
	$(".comt-meta span").hover(function(){
		$(this).children(".tooltip").css({ "opacity": 1, "pointer-events": "auto"});
	},function(){
		$(this).children(".tooltip").removeAttr("style");
	});
	/*
	$(".wrapper i").hover(function(){
		$(this).siblings(".tooltip").css({ "opacity": 1, "pointer-events": "auto"});
	},function(){
		$(this).siblings(".tooltip").css({ "opacity": 0, "pointer-events": "auto"});
	});
	*/
	//Upvote.create('runoobvote-id', {callback: vote_callback});
	var ajaxurl = 'https://www.runoob.com/wp-admin/admin-ajax.php';
	var callback = function(data) {
		//console.log($('#runoobvote-id').upvote('upvoted'));
		//console.log($('#runoobvote-id').upvote('downvoted'));
		//console.log(data);
		_vote_action = data.action;
		id_arr = data.id.split('-');
		um_id= id_arr[2];
		//console.log(um_id);
		
		var re = /^[1-9]+/;
		if (re.test(um_id)) { 
			var ajax_data = {
				_vote_action: _vote_action,
				action: "pinglun_zan",
				um_id: um_id,
				um_action: "ding"
			};
			//console.log(ajax_data);
			$.post(ajaxurl,ajax_data,function(status){
				//if(status.vote_num>999) {
				//	_voteHtml = '<span style="display: block; text-align: center;font-size: 20px; color: #6a737c; margin: 8px 0;">'+kFormatter(status.vote_num) +'</span>';
				//	$("#runoobvote-id-" + um_id + " .count").hide().after(_voteHtml);
				//}
				
			});
		}
	};
	if($('#comments').length && $('.upvotejs').length){
		$('.upvotejs').upvote({id: 7507, callback: callback});
	
		$.post(ajaxurl,{"action":"pinglun_zan","postid":7507},function(data){  
			$(data).each(function(key,value) {
				$("#runoobvote-id-" + value.commid + " .upvote").addClass(value.upvotejs_class);
				$("#runoobvote-id-" + value.commid + " .downvote").addClass(value.downvote_class);
				$("#runoobvote-id-" + value.commid + " .count").text(value.upvote_count);
			})
		},'json');
		
	}
	
	
});
function isBlank(str) {
    return (!str || /^\s*$/.test(str));
}
function kFormatter(num) {
	// return num;
    return Math.abs(num) > 999 ? Math.sign(num)*((Math.abs(num)/1000).toFixed(1)) + 'k' : Math.sign(num)*Math.abs(num)
}

</script>

<link rel="stylesheet" href="../0/qa.css?1.44">
<link rel="stylesheet" type="text/css" href="../0/simditor.min.css" />
<script type="text/javascript" src=""></script>
<script type="text/javascript" src=""></script>
<script type="text/javascript" src=""></script>
<script type="text/javascript" src=""></script>
<script type="text/javascript" src=""></script>
		<div class="sidebar-box ">
				

<style>	
.responsive_ad1 { display:none; }
@media(min-width: 800px) { .responsive_ad1 {  display:block;margin:0 auto;} }
</style>
<div id="ad-336280" >

<script async src=""
     crossorigin="anonymous"></script>
<!-- 移动版 自动调整 -->
<ins class="adsbygoogle"
     style="display:block"
     data-ad-client="ca-pub-5751451760833794"
     data-ad-slot="1691338467"
     data-ad-format="auto"
     data-full-width-responsive="true"></ins>
<script>
     (adsbygoogle = window.adsbygoogle || []).push({});
</script>
		</div>
				</div>
		
	</div>
</div>
	

<!-- 右边栏 -->
<div class="fivecol last right-column">

<style>
.sidebar-tree .double-li {
    width:300px;
}
.sidebar-tree .double-li li {
    width: 44%;
    line-height: 1.5em;
    border-bottom: 1px solid #ccc;
    float: left;
    display: inline;
}
</style>

    
        <div class="sidebar-box re-box re-box-large">
        <div class="sidebar-box recommend-here" style="margin: 0 auto;">
            <a href="javascript:void(0);" style="font-size: 16px; color:#64854c;font-weight:bold;"> <i class="fa fa-list" aria-hidden="true"></i> 分类导航</a>
        </div>
    <div class="sidebar-box sidebar-cate">
        
        <div class="sidebar-tree" >
            <ul><li style="margin: 0;"><a href="javascript:void(0);" class="tit"> HTML / CSS</a><ul class="double-li"><li><a title="HTML 教程" href="../html/html-tutorial.html">HTML 教程</a></li><li><a title="HTML5 教程" href="../html/html5-intro.html">HTML5 教程</a></li><li><a title="CSS 教程" href="../css/css-tutorial.html">CSS 教程</a></li><li><a title="CSS3 教程" href="../css3/css3-tutorial.html">CSS3 教程</a></li><li><a title="Bootstrap3 教程" href="../bootstrap/bootstrap-tutorial.html">Bootstrap3 教程</a></li><li><a title="Bootstrap4 教程" href="../bootstrap4/bootstrap4-tutorial.html">Bootstrap4 教程</a></li><li><a title="Bootstrap5 教程" href="../bootstrap5/bootstrap5-tutorial.html">Bootstrap5 教程</a></li><li><a title="Font Awesome 教程" href="../font-awesome/fontawesome-tutorial.html">Font Awesome 教程</a></li><li><a title="Foundation 教程" href="../foundation/foundation-tutorial.html">Foundation 教程</a></li></ul></li><li style="margin: 0;"><a href="javascript:void(0);" class="tit"> JavaScript</a><ul class="double-li"><li><a title="JavaScript 教程" href="../js/js-tutorial.html">JavaScript 教程</a></li><li><a title="HTML DOM 教程" href="../htmldom/htmldom-tutorial.html">HTML DOM 教程</a></li><li><a title="jQuery 教程" href="../jquery/jquery-tutorial.html">jQuery 教程</a></li><li><a title="AngularJS 教程" href="../angularjs/angularjs-tutorial.html">AngularJS 教程</a></li><li><a title="AngularJS2 教程" href="../angularjs2/angularjs2-tutorial.html">AngularJS2 教程</a></li><li><a title="Vue.js 教程" href="../vue2/vue-tutorial.html">Vue.js 教程</a></li><li><a title="Vue3 教程" href="../vue3/vue3-tutorial.html">Vue3 教程</a></li><li><a title="React 教程" href="../react/react-tutorial.html">React 教程</a></li><li><a title="TypeScript 教程" href="../typescript/ts-tutorial.html">TypeScript 教程</a></li><li><a title="jQuery UI 教程" href="../jqueryui/jqueryui-tutorial.html">jQuery UI 教程</a></li><li><a title="jQuery EasyUI 教程" href="../jeasyui/jqueryeasyui-tutorial.html">jQuery EasyUI 教程</a></li><li><a title="Node.js 教程" href="../nodejs/nodejs-tutorial.html">Node.js 教程</a></li><li><a title="AJAX 教程" href="../ajax/ajax-tutorial.html">AJAX 教程</a></li><li><a title="JSON 教程" href="../json/json-tutorial.html">JSON 教程</a></li><li><a title="Echarts 教程" href="../echarts/echarts-tutorial.html">Echarts 教程</a></li><li><a title="Chart.js 教程" href="../chartjs/chartjs-tutorial.html">Chart.js 教程</a></li><li><a title="Highcharts 教程" href="../highcharts/highcharts-tutorial.html">Highcharts 教程</a></li><li><a title="Google 地图 教程" href="../googleapi/google-maps-basic.html">Google 地图 教程</a></li></ul></li><li style="margin: 0;"><a href="javascript:void(0);" class="tit"> 服务端</a><ul class="double-li"><li><a title="Python 教程" href="../python3/python3-tutorial.html">Python 教程</a></li><li><a title="Python2.x 教程" href="../python/python-tutorial.html">Python2.x 教程</a></li><li><a title="Linux 教程" href="../linux/linux-tutorial.html">Linux 教程</a></li><li><a title="Docker 教程" href="../docker/docker-tutorial.html">Docker 教程</a></li><li><a title="Ruby 教程" href="../ruby/ruby-tutorial.html">Ruby 教程</a></li><li><a title="Java 教程" href="../java/java-tutorial.html">Java 教程</a></li><li><a title="C 教程" href="../c/c-tutorial.html">C 教程</a></li><li><a title="C++ 教程" href="../cplusplus/cpp-tutorial.html">C++ 教程</a></li><li><a title="Perl 教程" href="../perl/perl-tutorial.html">Perl 教程</a></li><li><a title="Servlet 教程" href="../servlet/servlet-tutorial.html">Servlet 教程</a></li><li><a title="JSP 教程" href="../jsp/jsp-tutorial.html">JSP 教程</a></li><li><a title="Lua 教程" href="../lua/lua-tutorial.html">Lua 教程</a></li><li><a title="Rust 教程" href="../rust/rust-tutorial.html">Rust 教程</a></li><li><a title="Scala 教程" href="../scala/scala-tutorial.html">Scala 教程</a></li><li><a title="Go 教程" href="../go/go-tutorial.html">Go 教程</a></li><li><a title="PHP 教程" href="../php/php-tutorial.html">PHP 教程</a></li><li><a title="数据结构与算法" href="../data-structures/data-structures-tutorial.html">数据结构与算法</a></li><li><a title="Django 教程" href="../django/django-tutorial.html">Django 教程</a></li><li><a title="Zookeeper 教程" href="../w3cnote/zookeeper-tutorial.html">Zookeeper 教程</a></li><li><a title="设计模式" href="../design-pattern/design-pattern-tutorial.html">设计模式</a></li><li><a title="正则表达式" href="../regexp/regexp-tutorial.html">正则表达式</a></li><li><a title="Maven 教程" href="../maven/maven-tutorial.html">Maven 教程</a></li><li><a title="Verilog 教程" href="../w3cnote/verilog-tutorial.html">Verilog 教程</a></li><li><a title="ASP 教程" href="../asp/asp-tutorial.html">ASP 教程</a></li><li><a title="AppML 教程" href="../appml/appml-tutorial.html">AppML 教程</a></li><li><a title="VBScript 教程" href="../vbscript/vbscript-tutorial.html">VBScript 教程</a></li></ul></li><li style="margin: 0;"><a href="javascript:void(0);" class="tit"> 数据库</a><ul class="double-li"><li><a title="SQL 教程" href="../sql/sql-tutorial.html">SQL 教程</a></li><li><a title="MySQL 教程" href="../mysql/mysql-tutorial.html">MySQL 教程</a></li><li><a title="PostgreSQL 教程" href="../postgresql/postgresql-tutorial.html">PostgreSQL 教程</a></li><li><a title="SQLite 教程" href="../sqlite/sqlite-tutorial.html">SQLite 教程</a></li><li><a title="MongoDB 教程" href="../mongodb/mongodb-tutorial.html">MongoDB 教程</a></li><li><a title="Redis 教程" href="../redis/redis-tutorial.html">Redis 教程</a></li><li><a title="Memcached 教程" href="../Memcached/Memcached-tutorial.html">Memcached 教程</a></li></ul></li><li style="margin: 0;"><a href="javascript:void(0);" class="tit"> 数据分析</a><ul class="double-li"><li><a title="Python 教程" href="../python3/python3-tutorial.html">Python 教程</a></li><li><a title="NumPy 教程" href="../numpy/numpy-tutorial.html">NumPy 教程</a></li><li><a title="Pandas 教程" href="../pandas/pandas-tutorial.html">Pandas 教程</a></li><li><a title="Matplotlib 教程" href="../matplotlib/matplotlib-tutorial.html">Matplotlib 教程</a></li><li><a title="Scipy 教程" href="../scipy/scipy-tutorial.html">Scipy 教程</a></li><li><a title="R 教程" href="../r/r-tutorial.html">R 教程</a></li><li><a title="Julia 教程" href="../julia/julia-tutorial.html">Julia 教程</a></li></ul></li><li style="margin: 0;"><a href="javascript:void(0);" class="tit"> 移动端</a><ul class="double-li"><li><a title="Android 教程" href="../w3cnote/android-tutorial-intro.html">Android 教程</a></li><li><a title="Swift 教程" href="../swift/swift-tutorial.html">Swift 教程</a></li><li><a title="jQuery Mobile 教程" href="../jquerymobile/jquerymobile-tutorial.html">jQuery Mobile 教程</a></li><li><a title="ionic 教程" href="../ionic/ionic-tutorial.html">ionic 教程</a></li><li><a title="Kotlin 教程" href="../kotlin/kotlin-tutorial.html">Kotlin 教程</a></li></ul></li><li style="margin: 0;"><a href="javascript:void(0);" class="tit"> XML 教程</a><ul class="double-li"><li><a title="XML 教程" href="../xml/xml-tutorial.html">XML 教程</a></li><li><a title="DTD 教程" href="../dtd/dtd-tutorial.html">DTD 教程</a></li><li><a title="XML DOM 教程" href="../dom/dom-tutorial.html">XML DOM 教程</a></li><li><a title="XSLT 教程" href="../xsl/xsl-tutorial.html">XSLT 教程</a></li><li><a title="XPath 教程" href="../xpath/xpath-tutorial.html">XPath 教程</a></li><li><a title="XQuery 教程" href="../xquery/xquery-tutorial.html">XQuery 教程</a></li><li><a title="XLink 教程" href="../xlink/xlink-tutorial.html">XLink 教程</a></li><li><a title="XPointer 教程" href="../xlink/xlink-tutorial.html">XPointer 教程</a></li><li><a title="XML Schema 教程" href="../schema/schema-tutorial.html">XML Schema 教程</a></li><li><a title="XSL-FO 教程" href="../xslfo/xslfo-tutorial.html">XSL-FO 教程</a></li><li><a title="SVG 教程" href="../svg/svg-tutorial.html">SVG 教程</a></li></ul></li><li style="margin: 0;"><a href="javascript:void(0);" class="tit"> ASP.NET</a><ul class="double-li"><li><a title="ASP.NET 教程" href="../aspnet/aspnet-tutorial.html">ASP.NET 教程</a></li><li><a title="C# 教程" href="../csharp/csharp-tutorial.html">C# 教程</a></li><li><a title="Web Pages 教程" href="../aspnet/webpages-intro.html">Web Pages 教程</a></li><li><a title="Razor 教程" href="../aspnet/razor-intro.html">Razor 教程</a></li><li><a title="MVC 教程" href="../aspnet/mvc-intro.html">MVC 教程</a></li><li><a title="Web Forms 教程" href="../aspnet/aspnet-intro.html">Web Forms 教程</a></li></ul></li><li style="margin: 0;"><a href="javascript:void(0);" class="tit"> Web Service</a><ul class="double-li"><li><a title="Web Service 教程" href="../webservices/webservices-tutorial.html">Web Service 教程</a></li><li><a title="WSDL 教程" href="../wsdl/wsdl-tutorial.html">WSDL 教程</a></li><li><a title="SOAP 教程" href="../soap/soap-tutorial.html">SOAP 教程</a></li><li><a title="RSS 教程" href="../rss/rss-tutorial.html">RSS 教程</a></li><li><a title="RDF 教程" href="../rdf/rdf-tutorial.html">RDF 教程</a></li></ul></li><li style="margin: 0;"><a href="javascript:void(0);" class="tit"> 开发工具</a><ul class="double-li"><li><a title="Eclipse 教程" href="../eclipse/eclipse-tutorial.html">Eclipse 教程</a></li><li><a title="Git 教程" href="../git/git-tutorial.html">Git 教程</a></li><li><a title="Svn 教程" href="../svn/svn-tutorial.html">Svn 教程</a></li><li><a title="Markdown 教程" href="../markdown/md-tutorial.html">Markdown 教程</a></li></ul></li><li style="margin: 0;"><a href="javascript:void(0);" class="tit"> 网站建设</a><ul class="double-li"><li><a title="HTTP 教程" href="../http/http-tutorial.html">HTTP 教程</a></li><li><a title="网站建设指南" href="../web/web-buildingprimer.html">网站建设指南</a></li><li><a title="浏览器信息" href="../browsers/browser-information.html">浏览器信息</a></li><li><a title="网站主机教程" href="../hosting/hosting-tutorial.html">网站主机教程</a></li><li><a title="TCP/IP 教程" href="../tcpip/tcpip-tutorial.html">TCP/IP 教程</a></li><li><a title="W3C 教程" href="../w3c/w3c-tutorial.html">W3C 教程</a></li><li><a title="网站品质" href="../quality/quality-tutorial.html">网站品质</a></li></ul></li></ul>            </div>
    
    </div>
    </div>
    <br>
    
    <div class="sidebar-box re-box re-box-large">
        <div class="sidebar-box recommend-here">
            <a href="javascript:void(0);">Advertisement</a>
        </div>
        <div class="re-600160" id="sidebar-right-re">
                <script async src=""></script>
        <!-- 侧栏1 -->
        <ins class="adsbygoogle"
             style="display:inline-block;width:160px;height:600px"
             data-ad-client="ca-pub-5751451760833794"
             data-ad-slot="4106274865"></ins>
        <script>
        (adsbygoogle = window.adsbygoogle || []).push({});
        </script>
                </div>
    </div>
</div></div>

</div>

<script>
var aid = 7507;
function coll() {
	$.post( '/wp-content/themes/runoob/option/user/userinfo.php', {aid:aid, action:"collarticle", opt:'add'},function( data ) {
		if(data.error==0) {
			$("#content").find("h1:first").find("a").attr("href","javascript:void(0);");
			$("#content").find("h1:first").find("img").attr("src","http://www.runoob.com/wp-content/themes/runoob/assets/img/coll2.png").css({width:32+"px",height:32+"px"});
		}
		alert(data.msg);
	},'json');
}
</script>


<!-- 反馈对话框开始 -->
<script src=""></script>
<link rel="stylesheet" href="../0/feedback.css?1.0" />
<script type="text/javascript">
$.feedback({
    ajaxURL: '/feedback/runoob_feedback.php',
	html2canvasURL: '/wp-content/themes/runoob/assets/feedback/stable/2.0/html2canvas.js',
	onClose: function () {
         window.location.reload();
    }
});
</script>
<!-- 反馈对话框结束 -->
<button class="feedback-btn feedback-btn-gray">反馈/建议</button>
<!-- 底部 -->
<div id="footer" class="mar-t50">
   <div class="runoob-block">
    <div class="runoob cf">
     <dl>
      <dt>
       在线实例
      </dt>
      <dd>
       &middot;<a target="_blank" href="../html/html-examples.html">HTML 实例</a>
      </dd>
      <dd>
       &middot;<a target="_blank" href="../css/css-examples.html">CSS 实例</a>
      </dd>
      <dd>
       &middot;<a target="_blank" href="../js/js-examples.html">JavaScript 实例</a>
      </dd>
      <dd>
       &middot;<a target="_blank" href="../ajx/ajax-examples.html">Ajax 实例</a>
      </dd>
       <dd>
       &middot;<a target="_blank" href="../jquery/jquery-examples.html">jQuery 实例</a>
      </dd>
      <dd>
       &middot;<a target="_blank" href="../xml/xml-examples.html">XML 实例</a>
      </dd>
      <dd>
       &middot;<a target="_blank" href="../java/java-examples.html">Java 实例</a>
      </dd>
     
     </dl>
     <dl>
      <dt>
      字符集&工具
      </dt>
      <dd>
       &middot; <a target="_blank" href="../charsets/html-charsets.html">HTML 字符集设置</a>
      </dd>
      <dd>
       &middot; <a target="_blank" href="../tags/html-ascii.html">HTML ASCII 字符集</a>
      </dd>
     <dd>
       &middot; <a target="_blank" href="https://c.runoob.com/front-end/6939/">JS 混淆/加密</a>
      </dd> 
      <dd>
       &middot; <a target="_blank" href="https://c.runoob.com/front-end/6232/">PNG/JPEG 图片压缩</a>
      </dd>
      <dd>
       &middot; <a target="_blank" href="../tags/html-colorpicker.html">HTML 拾色器</a>
      </dd>
      <dd>
       &middot; <a target="_blank" href="..//c.runoob.com/front-end/53">JSON 格式化工具</a>
      </dd>
      <dd>
       &middot; <a target="_blank" href="..//c.runoob.com/front-end/6680/">随机数生成器</a>
      </dd>
     </dl>
     <dl>
      <dt>
       最新更新
      </dt>
                   <dd>
       &middot;
      <a href="../matplotlib/matplotlib-imread.html" title="Matplotlib imread() 方法">Matplotlib imre...</a>
      </dd>
              <dd>
       &middot;
      <a href="../matplotlib/matplotlib-imsave.html" title="Matplotlib imsave() 方法">Matplotlib imsa...</a>
      </dd>
              <dd>
       &middot;
      <a href="../matplotlib/matplotlib-imshow.html" title="Matplotlib imshow() 方法">Matplotlib imsh...</a>
      </dd>
              <dd>
       &middot;
      <a href="../matplotlib/matplotlib-hist.html" title="Matplotlib 直方图">Matplotlib 直方图</a>
      </dd>
              <dd>
       &middot;
      <a href="../python3/python-func-object.html" title="Python object() 函数">Python object()...</a>
      </dd>
              <dd>
       &middot;
      <a href="../python3/python-ai-draw.html" title="Python AI 绘画">Python AI 绘画</a>
      </dd>
              <dd>
       &middot;
      <a href="../w3cnote/cursor-editor.html" title="神辅助 Cursor 编辑器，加入 GPT-4 让编码更轻松！">神辅助 Cursor ...</a>
      </dd>
             </dl>
     <dl>
      <dt>
       站点信息
      </dt>
      <dd>
       &middot;
       <a target="_blank" href="mailto:admin@runoob.com" rel="external nofollow">意见反馈</a>
       </dd>
      <dd>
       &middot;
      <a target="_blank" href="../disclaimer">免责声明</a>
       </dd>
      <dd>
       &middot;
       <a target="_blank" href="../aboutus">关于我们</a>
       </dd>
      <dd>
       &middot;
      <a target="_blank" href="../archives">文章归档</a>
      </dd>
    
     </dl>
    
     <div class="search-share">
      <div class="app-download">
        <div>
         <strong>关注微信</strong>
        </div>
      </div>
      <div class="share">
      <img width="128" height="128" src="/wp-content/themes/runoob/assets/images/qrcode.png" />
       </div>
     </div>
     
    </div>
   </div>
   <div class="w-1000 copyright">
     Copyright &copy; 2013-2023    <strong><a href="../" target="_blank">菜鸟教程</a></strong>&nbsp;
    <strong><a href="../" target="_blank">runoob.com</a></strong> All Rights Reserved. 备案号：<a target="_blank" rel="nofollow" href="https://beian.miit.gov.cn/">闽ICP备15012807号-1</a>
   </div>
  </div>
  <div class="fixed-btn">
    <a class="go-top" href="javascript:void(0)" title="返回顶部"> <i class="fa fa-angle-up"></i></a>
    <a class="qrcode"  href="javascript:void(0)" title="关注我们"><i class="fa fa-qrcode"></i></a>
    <a class="writer" style="display:none" href="javascript:void(0)"   title="标记/收藏"><i class="fa fa-star" aria-hidden="true"></i></a>
    <!-- qrcode modal -->
    <div id="bottom-qrcode" class="modal panel-modal hide fade in">
      <h4>微信关注</h4>
      <div class="panel-body"><img alt="微信关注" width="128" height="128" src="/wp-content/themes/runoob/assets/images/qrcode.png"></div> 
    </div>
  </div>

 <div style="display:none;">
<script async src="https://www.googletagmanager.com/gtag/js?id=UA-84264393-2"></script>
<script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());

  gtag('config', 'UA-84264393-2');
</script>
<script>
var _hmt = _hmt || [];
(function() {
  var hm = document.createElement("script");
  hm.src = "https://hm.baidu.com/hm.js?3eec0b7da6548cf07db3bc477ea905ee";
  var s = document.getElementsByTagName("script")[0]; 
  s.parentNode.insertBefore(hm, s);
})();
</script>

</div>
<script>
window.jsui={
    www: 'https://www.runoob.com',
    uri: 'https://www.runoob.com/wp-content/themes/runoob'
};
</script>

<script src=""></script>
<script src=""></script>

</body>
</html>